1

我正在尝试获取使用数组获取的目录树的倒数第二级。当它到达 Console.WriteLine 部分时,它不显示任何内容,似乎跳过了整行。

foreach (string file in files)   
{   
    string thepathoflife = Path.GetFullPath(file);
    string filetocopy = file;
    string location = file;
    bool b = false;
    string extension = Path.GetExtension(file);
    string thenameofdoom = Path.GetFileNameWithoutExtension(file);
    string filename = Path.GetFileName(file);


    //here is my attempt
    string dirthing = Path.GetDirectoryName(filename); //here is my attempt
    System.Console.WriteLine("" + dirthing); //here is my attempt
4

2 回答 2

3

您可以调用Path.GetDirectoryName两次以向上遍历文件夹层次结构:

Path.GetDirectoryName(Path.GetDirectoryName(Path.GetFullPath(file)))

null如果您在层次结构中太“高”,它将返回。

于 2012-05-01T13:36:50.570 回答
2

这里有一些例子:

var path = Path.GetFullPath("example.png");
// path == "C:\\Users\\dtb\\Desktop\\example.png"

Path.GetFileName(path)                              // "example.png"
Path.GetFileNameWithoutExtension(path)              // "example"
Path.GetExtension(path)                             // ".png"

Path.GetDirectoryName(Path.GetFileName(path))       // ""

Path.GetDirectoryName(path)                         // "C:\\Users\\dtb\\Desktop"
Path.GetDirectoryName(Path.GetDirectoryName(path))  // "C:\\Users\\dtb"
于 2012-05-01T13:40:20.307 回答