paulwhit paulwhit - 1 year ago 193
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];
fileName = hrefLink;

return fileName;

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download