Problem
This is the approach I use to get the file name from a string URI. What can I do to improve its sturdiness?
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;
}
Asked by paulwhit
Solution #1
Simply create a System.Uri object, check if it’s a file with IsFile, and then use Uri.LocalPath to extract the filename.
This is significantly safer because it also allows you to verify the URI’s validity.
In response to a comment, I’ve made the following changes:
I’d use the following command to acquire the whole filename:
Uri uri = new Uri(hreflink);
if (uri.IsFile) {
string filename = System.IO.Path.GetFileName(uri.LocalPath);
}
This handles all error checking for you and is platform-independent. All of the unique situations are handled quickly and efficiently for you.
Answered by Reed Copsey
Solution #2
Uri. http urls aren’t supported by IsFile. Only “file:/” is supported. “The IsFile property is true when the Scheme property equals UriSchemeFile,” according to MSDN. As a result, you can’t rely on it.
Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
Answered by Le Zhang
Solution #3
The majority of other answers are either incomplete or ignore anything after the path (query string/hash).
readonly static Uri SomeBaseUri = new Uri("http://canbeanything");
static string GetFileNameFromUrl(string url)
{
Uri uri;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
uri = new Uri(SomeBaseUri, url);
return Path.GetFileName(uri.LocalPath);
}
Test results:
GetFileNameFromUrl(""); // ""
GetFileNameFromUrl("test"); // "test"
GetFileNameFromUrl("test.xml"); // "test.xml"
GetFileNameFromUrl("/test.xml"); // "test.xml"
GetFileNameFromUrl("/test.xml?q=1"); // "test.xml"
GetFileNameFromUrl("/test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3#aidjsf"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/a/b/c/d"); // "d"
GetFileNameFromUrl("http://www.a.com/a/b/c/d/e/"); // ""
Answered by Ronnie Overby
Solution #4
For http urls, the accepted answer is problematic. In addition, Uri. LocalPath performs Windows-specific conversions and, as one user pointed out, includes query strings. Uri is a better option. AbsolutePath
For http urls, the proper procedure is as follows:
Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);
Answered by Kostub Deshmukh
Solution #5
This, I believe, will suffice:
var uri = new Uri(hreflink);
var filename = uri.Segments.Last();
Answered by Zeus82
Post is based on https://stackoverflow.com/questions/1105593/get-file-name-from-uri-string-in-c-sharp