在C#中的URI字符串获取文件名 [英] Get file name from URI string in C#
问题描述
我有一个从字符串URI抓住的文件名此方法。我能做些什么,使之更加强健?
私人字符串用GetFileName(字符串hrefLink)
{
字符串[] =零件hrefLink.Split('/');
字符串文件名=; 如果(parts.Length大于0)
文件名=零件[parts.Length - 1];
其他
文件名= hrefLink; 返回文件名;
}
您可以只是做一个的System.Uri对象,并使用ISFILE来验证它的一个文件,然后的 Uri.LocalPath 提取的文件名。
这是安全得多,因为它为您提供检查URI的有效性以及一个手段。
编辑回应评论:
要得到公正的完整文件名,我会使用:
开放的URI =新的URI(hreflink);
如果(uri.IsFile){
字符串文件名= System.IO.Path.GetFileName(uri.LocalPath);
}
这做了所有的错误检查你的,与平台无关。所有的特殊情况下会为你快速,方便地处理。
I have this method for grabbing the file name from a string URI. What can I do to make it more robust?
private string GetFileName(string hrefLink)
{
string[] parts = hrefLink.Split('/');
string fileName = "";
if (parts.Length > 0)
fileName = parts[parts.Length - 1];
else
fileName = hrefLink;
return fileName;
}
You can just make a System.Uri object, and use IsFile to verify it's a file, then Uri.LocalPath to extract the filename.
This is much safer, as it provides you a means to check the validity of the URI as well.
Edit in response to comment:
To get just the full filename, I'd use:
Uri uri = new Uri(hreflink);
if (uri.IsFile) {
string filename = System.IO.Path.GetFileName(uri.LocalPath);
}
This does all of the error checking for you, and is platform-neutral. All of the special cases get handled for you quickly and easily.
这篇关于在C#中的URI字符串获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!