从字符串中获取文件名

你能帮我找到字符串中的文件名吗? 现在我有一串内容,如“C:\ xxxx \ xxxx \ xxxx \ abc.pdf”。 但我只想要文件名即。 abc.pdf。 如何使用字符串函数?

使用Path.GetFileName

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

请注意,这假定名称的最后一部分是文件 – 它不会检查。 因此,如果你给它“C:\ Windows \ System32”它会声称System32的文件名,即使它实际上是一个目录。 (但是, File.Exists “C:\ Windows \ System32 \”将返回一个空字符串。)您可以使用File.Exists检查文件是否存在如果有帮助,则检查文件而不是目录

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

使用Path.GetFileName()方法

来自MSDN页面的(已编辑)示例:

 string fileName = @"C:\xxxx\xxxx\xxxx\abc.pdf"; string path = @"C:\xxxx\xxxx\xxxx\"; string path2 = @"C:\xxxx\xxxx\xxxx"; string result; result = Path.GetFileName(fileName); Console.WriteLine("GetFileName('{0}') returns '{1}'", fileName, result); result = Path.GetFileName(path); Console.WriteLine("GetFileName('{0}') returns '{1}'", path, result); result = Path.GetFileName(path2); Console.WriteLine("GetFileName('{0}') returns '{1}'", path2, result); 

此代码生成类似于以下内容的输出:

 GetFileName('C:\xxxx\xxxx\xxxx\abc.pdf') returns 'abc.pdf' GetFileName('C:\xxxx\xxxx\xxxx\') returns '' GetFileName('C:\xxxx\xxxx\xxxx') returns 'xxxx' 

Sytem.IO.FileInfo也很酷:在你的情况下,你可以做到

 FileInfo fi = new FileInfo("C:\xxxx\xxxx\xxxx\abc.pdf"); string name = fi.Name; // it gives you abc.pdf 

然后你可以得到其他几条信息:
文件确实存在吗? fi.Exists给你答案
它的扩展是什么? 见fi.Extension
它的目录名称是什么? 见fi.Directory
等等

看看FileInfo的所有成员,您可能会发现一些有趣的东西满足您的需求

使用System.IO.Path的方法,尤其是Path.GetFileName 。

System.IO.Path.GetFilename(yourFilename)将返回文件的名称。