【问题标题】:2nd to last level of a directory tree目录树的第二层到最后一层
【发布时间】:2012-05-01 13:33:59
【问题描述】:

我正在尝试获取我使用数组获取的目录树的倒数第二级。 当它到达 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

【问题讨论】:

    标签: c# file tree filesystems directory


    【解决方案1】:

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

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

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

    【讨论】:

    • 我想找到文件所在的文件夹。我正在使用 System.Console.WriteLine("" + dirthing);看看它是否有效。
    • 这行得通,我花了一秒钟才弄清楚是什么让它不显示,这是一个没有导致异常的小错字
    • 这不是您在示例中显示的内容,您显示的是上面的路径。例如 c:\a\b\c.txt 您的示例将 c:\a 作为路径。
    【解决方案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"
    

    【讨论】:

    • 问题是,我使用的是字符串 thepathoflife = Path.GetFullPath(file);找到完整路径。
    • @shred1894 不,实际上,你不是。你得到它,然后从不真正使用它......
    • 我确实使用它,以后,很久以后。我实际上并没有给出整个 200 多行的脚本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多