更新时间:2023-02-23 18:37:14
您可以只是做一个的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.