Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to get the file extension from a URL

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?

like image 385
z3nth10n Avatar asked Sep 02 '25 11:09

z3nth10n


1 Answers

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

like image 110
Alex from Jitbit Avatar answered Sep 04 '25 06:09

Alex from Jitbit