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#?
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);
You could try:
var path = @"/Users/smcho/filegen_from_directory/AIRPassthrough/";
var dirName = new DirectoryInfo(path).Name;
You're looking for Path.GetFileName
.
Note that this won't work if the path ends in a \
.
This is a slightly different answer, depending on what you have. If you have a list of files and need to get the name of the last directory that the file is in you can do this:
string path = "/attachments/1828_clientid/2938_parentid/somefiles.docx";
string result = new DirectoryInfo(path).Parent.Name;
This will return "2938_parentid"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With