pro*_*eek 142 c# string filepath
我需要获取当前目录的最后一部分,例如/Users/smcho/filegen_from_directory/AIRPassthrough,我需要获取AIRPassthrough.
使用python,我可以使用此代码获取它.
import os.path
path = "/Users/smcho/filegen_from_directory/AIRPassthrough"
print os.path.split(path)[-1]
Run Code Online (Sandbox Code Playgroud)
要么
print os.path.basename(path)
Run Code Online (Sandbox Code Playgroud)
我怎么能用C#做同样的事情?
在回答者的帮助下,我找到了我需要的东西.
using System.Linq;
string fullPath = Path.GetFullPath(fullPath).TrimEnd(Path.DirectorySeparatorChar);
string projectName = fullPath.Split(Path.DirectorySeparatorChar).Last();
Run Code Online (Sandbox Code Playgroud)
要么
string fullPath = Path.GetFullPath(fullPath).TrimEnd(Path.DirectorySeparatorChar);
string projectName = Path.GetFileName(fullPath);
Run Code Online (Sandbox Code Playgroud)
cod*_*ast 166
你可以尝试:
var path = @"/Users/smcho/filegen_from_directory/AIRPassthrough/";
var dirName = new DirectoryInfo(path).Name;
Run Code Online (Sandbox Code Playgroud)
SLa*_*aks 121
你在找Path.GetFileName.
请注意,如果路径以a结尾,则不起作用\.
Jak*_*lås 10
那么,要准确回答你的问题标题:-)
var lastPartOfCurrentDirectoryName =
Path.GetFileName(Environment.CurrentDirectory);
Run Code Online (Sandbox Code Playgroud)
这是一个稍微不同的答案,取决于你有什么.如果您有一个文件列表,并且需要获取该文件所在的最后一个目录的名称,则可以执行以下操作:
string path = "/attachments/1828_clientid/2938_parentid/somefiles.docx";
string result = new DirectoryInfo(path).Parent.Name;
Run Code Online (Sandbox Code Playgroud)
这将返回"2938_parentid"
而不是使用'/'来调用split,更好地使用Path.DirectorySeparatorChar:
像这样:
path.split(Path.DirectorySeparatorChar).Last()
Run Code Online (Sandbox Code Playgroud)
var lastFolderName = Path.GetFileName(
path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
Run Code Online (Sandbox Code Playgroud)
如果路径恰好包含正斜杠分隔符或反斜杠分隔符,则此方法有效。