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

10

209

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);
Ballance answered 16/5, 2011 at 13:39 Comment(2)
Several possible duplicates: #4471810 #2408405 https://mcmap.net/q/128928/-get-directory-from-full-pathPianism
In python, you should rather do os.path.basename(path).Dunsany
C
145

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

Crosstie answered 16/5, 2011 at 13:42 Comment(8)
@anti: Wrong; I tried it. Strings are strings. Paste Path.GetFileName("/Users/smcho/filegen_from_directory/AIRPassthrough") into LINQPad if you don't believe me.Crosstie
@antisanity No, it will return the directory name, but it probably is not exactly what the question was about.Apolitical
@Jakob: Given the title, I think this is what the question is about.Crosstie
I think maybe it dont work because windows directory seperator is \ not /Negotiable
@Light: It does work; try it. The Path class handles both separators.Crosstie
To have this work with a directory retrieved by Directory.GetDirectories use: string directoryName = Path.GetFileName(directory.TrimEnd(Path.DirectorySeparatorChar));Popularize
What if you want a directory and not a file name?Coauthor
@KyleDelaney: It makes no difference; this just manipulates strings.Crosstie
H
279

You could try:

var path = @"/Users/smcho/filegen_from_directory/AIRPassthrough/";
var dirName = new DirectoryInfo(path).Name;
Horehound answered 16/5, 2011 at 13:48 Comment(4)
I like this better than the chosen answer. (Ab)using GetFileName is semantically wrong since it's a directory you're trying to retrieve. Also, to make GetFileName deterministic means you have to account for the possibility of a trailing forward slash or backslash, and trim it off, which is ugly.Sturm
var dirName = new DirectoryInfo(Path.GetDirectoryName(pathWithFilename)).Name //is betterPlop
@kernowcode I believe that would return "filegen_from_directory" instead of ''AIRPassthrough" as requested by the OP.Horehound
@SimonBrangwin I thought everything is a file in Linux :)Whom
C
145

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

Crosstie answered 16/5, 2011 at 13:42 Comment(8)
@anti: Wrong; I tried it. Strings are strings. Paste Path.GetFileName("/Users/smcho/filegen_from_directory/AIRPassthrough") into LINQPad if you don't believe me.Crosstie
@antisanity No, it will return the directory name, but it probably is not exactly what the question was about.Apolitical
@Jakob: Given the title, I think this is what the question is about.Crosstie
I think maybe it dont work because windows directory seperator is \ not /Negotiable
@Light: It does work; try it. The Path class handles both separators.Crosstie
To have this work with a directory retrieved by Directory.GetDirectories use: string directoryName = Path.GetFileName(directory.TrimEnd(Path.DirectorySeparatorChar));Popularize
What if you want a directory and not a file name?Coauthor
@KyleDelaney: It makes no difference; this just manipulates strings.Crosstie
S
24

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"

Servais answered 22/4, 2015 at 18:26 Comment(0)
C
12

Well, to exactly answer your question title :-)

var lastPartOfCurrentDirectoryName = 
   Path.GetFileName(Environment.CurrentDirectory);
Cuddy answered 16/5, 2011 at 13:55 Comment(0)
T
10

rather then using the '/' for the call to split, better to use the Path.DirectorySeparatorChar :

like so:

path.split(Path.DirectorySeparatorChar).Last() 
Trudeau answered 16/5, 2011 at 13:50 Comment(3)
One thing I don't like about using this solution is that it makes an assumption as to where the string is coming from. What if they're reading *nix logs on a Windows System? Then the wrong character will be utilized and you'll end up with the entire path, rather than the intended effect. Just my 2 cents.Impressionist
i agree with you on this. the OP said 'last part of current directory' so for that, this is fine.Hydroelectric
@BobG So from your point of view, what is better solution?Araminta
B
7
var lastFolderName = Path.GetFileName(
    path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));

This works if the path happens to contain forward slash separators or backslash separators.

Blunder answered 27/3, 2015 at 11:29 Comment(1)
The applied location of .TrimEnd() is incorrect. It should be applied to path, not Path.GetFileName. See the answer from @PopularizePedicure
D
2

Try this:

String newString = "";
String oldString = "/Users/smcho/filegen_from_directory/AIRPassthrough";

int indexOfLastSlash = oldString.LastIndexOf('/');

newString = oldString.Substring(indexOfLastSlash, oldString.Length);

Code may be off (I haven't tested it) but the idea should work.

Dyslexia answered 16/5, 2011 at 13:47 Comment(0)
R
2

This works perfectly fine with me :)

Path.GetFileName(path.TrimEnd('\\')
Retire answered 26/1, 2019 at 7:36 Comment(0)
T
2

You can also use the Uri class.

new Uri("file:///Users/smcho/filegen_from_directory/AIRPassthrough").Segments.Last()

You may prefer to use this class if you want to get some other segment, or if you want to do the same thing with a web address.

Theca answered 10/4, 2020 at 1:37 Comment(0)
L
0

You can try below code :

Path.GetFileName(userpath)

Larousse answered 12/6, 2019 at 10:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.