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

时光怂恿深爱的人放手 提交于 2019-11-28 06:39:33

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

codybartfast

You could try:

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

The easiest way to get the folder name is to initialize an instance of DirectoryInfo with the path.

string path = "/Users/smcho/filegen_from_directory/AIRPassthrough";
string result = new DirectoryInfo(path).Name;

This works the same if the path ends with or without a directory seperator and if either a forward or backwards seperator is used.

Well, to exactly answer your question title :-)

var lastPartOfCurrentDirectoryName = 
   Path.GetFileName(Environment.CurrentDirectory);

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"

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

like so:

path.split(Path.DirectorySeparatorChar).Last() 
var lastFolderName = Path.GetFileName(
    path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));

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

Try this:

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

int indexOfLastSlash = oldString.LastIndexOf('/', 0, oldString.length());

newString = oldString.subString(indexOfLastSlash, oldString.length());

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

This works perfectly fine with me :)

Path.GetFileName(path.TrimEnd('\\')

You can try below code :

Path.GetFileName(userpath)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!