Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the second to last directory in a path string in C#

For example,

string path = @"C:\User\Desktop\Drop\images\";

I need to get only @"C:\User\Desktop\Drop\

Is there any easy way of doing this?

like image 971
user1384603 Avatar asked Dec 18 '12 12:12

user1384603


3 Answers

You can use the Path and Directory classes:

DirectoryInfo parentDir = Directory.GetParent(Path.GetDirectoryName(path));
string parent = parentDir.FullName; 

Note that you would get a different result if the path doesn't end with the directory-separator char \. Then images would be understood as filename and not as directory.

You can also use a subsequent call of Path.GetDirectoryName

string parent = Path.GetDirectoryName(Path.GetDirectoryName(path));

This behaviour is documented here:

Because the returned path does not include the DirectorySeparatorChar or AltDirectorySeparatorChar, passing the returned path back into the GetDirectoryName method will result in the truncation of one folder level per subsequent call on the result string. For example, passing the path "C:\Directory\SubDirectory\test.txt" into the GetDirectoryName method will return "C:\Directory\SubDirectory". Passing that string, "C:\Directory\SubDirectory", into GetDirectoryName will result in "C:\Directory".

like image 188
Tim Schmelter Avatar answered Oct 03 '22 14:10

Tim Schmelter


This will return "C:\User\Desktop\Drop\" e.g. everything but the last subdir

string path = @"C:\User\Desktop\Drop\images";
string sub = path.Substring(0, path.LastIndexOf(@"\") + 1);

Another solution if you have a trailing slash:

string path = @"C:\User\Desktop\Drop\images\";
var splitedPath = path.Split('\\');
var output = String.Join(@"\", splitedPath.Take(splitedPath.Length - 2));
like image 40
Blachshma Avatar answered Oct 03 '22 15:10

Blachshma


var parent = ""; 
If(path.EndsWith(System.IO.Path.DirectorySeparatorChar) || path.EndsWith(System.IO.Path.AltDirectorySeparatorChar))
{
  parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
  parent = Directory.GetParent(Path.GetDirectoryName(path)).FullName;
}
else
  parent = Path.GetDirectoryName(path);

As i commented GetDirectoryName is self collapsing it returns path without tralling slash - allowing to get next directory.Using Directory.GetParent for then clouse is also valid.

like image 28
drk Avatar answered Oct 03 '22 16:10

drk