且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从字符串获取文件名

更新时间:2022-05-07 22:30:58

使用 Path.GetFileName :

string full = @"C:\xxxx\xxxx\xxxx\abc.pdf";
string file = Path.GetFileName(full);
Console.WriteLine(file); // abc.pdf

请注意,这个假定名称的最后一部分是文件-不会检查.因此,如果将其命名为"C:\ Windows \ System32",则即使它实际上是一个目录,它也会声明文件名System32.(但是,传递"C:\ Windows \ System32 \"将返回一个空字符串.)您可以使用

Note that this assumes the last part of the name is a file - it doesn't check. So if you gave it "C:\Windows\System32" it would claim a filename of System32, even though that's actually a directory. (Passing in "C:\Windows\System32\" would return an empty string, however.) You can use File.Exists to check that a file exists and is a file rather than a directory if that would help.

此方法也不会检查目录层次结构中的所有其他元素是否存在-因此您可以传入"C:\ foo \ bar \ baz.txt",即使foo和bar,它也会返回baz.txt不存在.

This method also doesn't check that all the other elements in the directory hierarchy exist - so you could pass in "C:\foo\bar\baz.txt" and it would return baz.txt even if foo and bar don't exist.