More of paths and such

与世无争的帅哥 提交于 2019-12-11 16:26:54

问题


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:


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:.



来源:https://stackoverflow.com/questions/10352190/more-of-paths-and-such

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!