Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 640
prosseek Avatar asked May 16 '11 13:05

prosseek


3 Answers

You could try:

var path = @"/Users/smcho/filegen_from_directory/AIRPassthrough/";
var dirName = new DirectoryInfo(path).Name;
like image 111
codybartfast Avatar answered Nov 01 '22 10:11

codybartfast


You're looking for Path.GetFileName.
Note that this won't work if the path ends in a \.

like image 144
SLaks Avatar answered Nov 01 '22 08:11

SLaks


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"

like image 21
ProVega Avatar answered Nov 01 '22 09:11

ProVega