More of paths and such

2019-08-27 03:09发布

I am making a script that finds what the 2nd folder in the path is, how would I do this?

dirA
dirB/C ---- I need dirB
indirB - dirD/E
indirE - The file

I need to find the name of the folder in the 2nd level that paths to the file (I marked it with stars).

how would I go about finding this

1条回答
劫难
2楼-- · 2019-08-27 03:41

How about this extension:

public static class StringExtensions
{
    public static String PathLevel(this String path, int level)
    {
        if (path == null) throw new ArgumentException("Path must not be null", "path");
        if (level < 0) throw new ArgumentException("Level must be >= 0", "level");

        var levels = path.Split(Path.DirectorySeparatorChar);
        return levels.Length > level ? levels[level] : null;
    }
}

testing:

var path = @"C:\Temp\Level2\Level3\Level4\File.txt";
var secondLevel = path.PathLevel(2); // => "Level2"

It splits the path by DirectorySeparatorChar to a String[]. You wanted the second level(the third element), this returns "Level2". Note that the first element is C:.

查看更多
登录 后发表回答