Reputation: 123
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
Upvotes: 0
Views: 88
Reputation: 460238
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:
.
Upvotes: 2