paulwhit paulwhit - 1 month ago 19
C# Question

Get file name from URI string in C#

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;
}

Answer

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.

Comments