Web file image/video header

945 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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);
}
0
On

You can check resp.Headers.Get("Content-Type") in response header.

For example, it will be image/jpeg for jpg file.

See list of available content types.