Get the (last part of) current directory name in C#

prosseek picture prosseek · May 16, 2011 · Viewed 145.3k times · Source

I need to get the last part of current directory, for example from /Users/smcho/filegen_from_directory/AIRPassthrough, I need to get AIRPassthrough.

With python, I can get it with this code.

import os.path

path = "/Users/smcho/filegen_from_directory/AIRPassthrough"
print os.path.split(path)[-1]

Or

print os.path.basename(path)

How can I do the same thing with C#?

ADDED

With the help from the answerers, I found what I needed.

using System.Linq;
string fullPath = Path.GetFullPath(fullPath).TrimEnd(Path.DirectorySeparatorChar);
string projectName  = fullPath.Split(Path.DirectorySeparatorChar).Last();

or

string fullPath = Path.GetFullPath(fullPath).TrimEnd(Path.DirectorySeparatorChar);
string projectName = Path.GetFileName(fullPath);

Answer

codybartfast picture codybartfast · May 16, 2011

You could try:

var path = @"/Users/smcho/filegen_from_directory/AIRPassthrough/";
var dirName = new DirectoryInfo(path).Name;