Search code examples
c#http-headersfile-typehttp-content-lengthwebimage

Web file image/video header


In C#, is it possible to detect if the web address of a file is an image, or a video? Is there such a header value for this?

I have the following code that gets the filesize of a web file:

System.Net.WebRequest req = System.Net.HttpWebRequest.Create("http://test.png");
req.Method = "HEAD";
using (System.Net.WebResponse resp = req.GetResponse())
{
    int ContentLength;
    if(int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
    { 
        //Do something useful with ContentLength here 
    }
}

Can this code be modified to see if a file is an image or a video?

Thanks in advance


Solution

  • What you're looking for is the "Content-Type" header

    string uri = "http://assets3.parliament.uk/iv/main-large//ImageVault/Images/id_7382/scope_0/ImageVaultHandler.aspx.jpg";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "HEAD";
    
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        var contentType = response.Headers["Content-Type"];
    
        Console.WriteLine(contentType);
    }