Questions
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;
}
Answers
http://msdn.microsoft.com/en-us/library/system.uri.localpath.aspx
http://msdn.microsoft.com/en-us/library/system.uri.localpath.aspx
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.
Source
License : cc by-sa 3.0
http://stackoverflow.com/questions/1105593/get-file-name-from-uri-string-in-c-sharp
Related