cyberbemon
cyberbemon

Reputation: 3190

Extracting folder names from path

I have a path like this

   Path =  C:\Users\cyberbemon\Documents\Development\Image tool\sources\AL001\2014-05-17\ImageTool\output.xml

I want to extract the folder names 2014-05-17 and AL001 They will later be used as a filename for eg: 140517-AL001.xml.

The problem is the paths are dynamic, so instead of 2014-05-17 and AL001 I could have something different like 2012-05-17 and AL401. The one thing that remains the same is ImageTool\output.xml

So what's the C# equivalent of GetParentof(GetParentof(\ImageTool\output.xml))

When looking around I came across this New DirectoryInfo(Path).Name This for me returns ImageTool and that's no use to me.

Upvotes: 0

Views: 118

Answers (4)

Steve
Steve

Reputation: 216293

If you can guarantee that there are always 3 directory levels then

string p =  @"C:\Users\cyberbemon\Documents\Development\Image tool\sources\AL001\2014-05-17\ImageTool\output.xml";
DirectoryInfo di = new DirectoryInfo(p);
string p1 = di.Parent.Parent.Name;
string p2 = di.Parent.Parent.Parent.Name;

The Parent property of a DirectoryInfo class is another DirectoryInfo, so it just a matter to place the appropriate number of recursive call to Parent

I should note that the DirectoryInfo class works also if you pass a file at its constructor. If you want to stick to the exact nature of the string then you could use the FileInfo class and recover the parent DirectoryInfo using:

FileInfo fi = new FileInfo(p);
string p1 = fi.Directory.Parent.Name;

Upvotes: 7

Pierre-Olivier Goulet
Pierre-Olivier Goulet

Reputation: 988

You can use System.IO.Path.GetDirectoryName(path) to get directory from a file/directory. In your case it would be

Path.GetFileName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(path))))

But it would be more elegant to create a recursive method that take a path and a level in parameters and returns the Directory name.

Upvotes: 0

Bedford
Bedford

Reputation: 1186

Splitting the string (not as elegant as using IO functions though):

string Path =  @"C:\Users\cyberbemon\Documents\Development\Image tool\sources\AL001\2014-05-17\ImageTool\output.xml";
string[] components = Path.Split('\\');
string p1 = components[components.Length - 2];
string p2 = components[components.Length - 3];

Upvotes: 0

Jeffrey Wieder
Jeffrey Wieder

Reputation: 2376

You could also just split your string on the directory separator and navigate from the end of the array to the point you want.

        string[] pathParts = path.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 0

Related Questions