从字符串获取文件名 [英] Getting File name from the String

查看:54
本文介绍了从字符串获取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能帮我从字符串中查找文件名吗?现在我有一个内容字符串,例如"C:\ xxxx \ xxxx \ xxxx \ abc.pdf".但我只想要文件名即.abc.pdf.通过使用字符串函数将如何获得它?

Could you help me for finding the file name from the string. Now i have one string of content like "C:\xxxx\xxxx\xxxx\abc.pdf". But i want only the file name ie. abc.pdf. How it will get by using string functions?

推荐答案

使用 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.

这篇关于从字符串获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆