如何仅获取文件路径名的一部分

本文关键字:一部分 路径名 文件 何仅 获取 | 更新日期: 2023-09-27 17:57:05

这是一行:

string t = Path.GetDirectoryName(file1);

结果是:

C:''Users''bout0_000''AppData''Local''Extracting_Frames''Extracting_Frames''dat file''converted.avi''histogramValues.dat

我希望它只包含:converted.avi.

PS:converted.avi不是文件名,而是路径名。我想获取路径的最后一部分,即没有文件名的最后一个子目录。

如何仅获取文件路径名的一部分

如果converted.avi是文件名,则使用这个

string t = Path.GetFileName(file1);

文档:http://msdn.microsoft.com/en-gb/library/system.io.path.getfilename.aspx

但是,如果这是目录的名称,则可以从已有的结果中提取最后一个反斜杠之后的所有内容。

var path = Path.GetDirectoryName(fileName);
var parentFolder = path.Substring(path.LastIndexOf('''')+1);

现场示例:http://rextester.com/RYPMI91227

你想要 FileInfo.Name:

http://msdn.microsoft.com/en-us/library/system.io.fileinfo.name(v=vs.80).aspx

所以像这样:

var fileInfo = new FileInfo(file1);
var fileName = fileInfo.Name; // this will only contain converted.avi

使用 Path.Get文件名将返回文件名

使用文件信息

FileInfo info = new FileInfo(yourFilePath);
var filename = info.Name;

http://msdn.microsoft.com/en-us/library/system.io.fileinfo(v=vs.100).aspx

使用 Path 类的 GetFileName() 函数