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

前端 未结 7 1313
囚心锁ツ
囚心锁ツ 2021-02-12 06:48

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:

h         


        
7条回答
  •  情歌与酒
    2021-02-12 07:28

    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

提交回复
热议问题