I want to know that for make sure that the file that will be download from my script will have the extension I want.
The file will not be at URLs like:
http://example.com/this_url_will_download_a_file
Or maybe yes, but, I think that I will only use that kind of URL:
http://example.com/file.jpg
I will not check it with: Url.Substring(Url.LastIndexOf(".") - 3, 3)
because this is a very poor way.
So, what do you recommend me to do?
here's a simple one I use. Works with parameters, with absolute and relative URLs, etc. etc.
public static string GetFileExtensionFromUrl(string url)
{
url = url.Split('?')[0];
url = url.Split('/').Last();
return url.Contains('.') ? url.Substring(url.LastIndexOf('.')) : "";
}
Unit test if you will
[TestMethod]
public void TestGetExt()
{
Assert.IsTrue(Helpers.GetFileExtensionFromUrl("../wtf.js?x=wtf")==".js");
Assert.IsTrue(Helpers.GetFileExtensionFromUrl("wtf.js")==".js");
Assert.IsTrue(Helpers.GetFileExtensionFromUrl("http://www.com/wtf.js?wtf")==".js");
Assert.IsTrue(Helpers.GetFileExtensionFromUrl("wtf") == "");
Assert.IsTrue(Helpers.GetFileExtensionFromUrl("") == "");
}
Tune for your own needs.
P.S. Do not use Path.GetExtension
cause it does not work with query-string params
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With