目录树的第二级到最后一级

时间:2012-05-01 13:34:00

标签: c# file tree filesystems directory

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

2 个答案:

答案 0 :(得分:3)

您可以拨打Path.GetDirectoryName两次以走向文件夹层次结构:

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

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

答案 1 :(得分: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"