CodeToad CodeToad - 1 year ago 200
ASP.NET (C#) Question

.NET WebClient.DownloadData get file type?

In order to handle cases of downloading data from a url that has no file extension,
I need to know what the file type is.

for example, how can the WebClient.DownloadData method reveal that it downloaded a png [edit: jpeg] image using the url below?

I did not find anything in the documentation that describes how to do this.

Answer Source

It can't, directly.

If you trust the headers the web server sends back, you could use a different HTTP client (e.g. WebRequest or HttpClient) to make the entire response available rather than just the body. You can then look at the Content-Type header.

Other than that, you'll need to look at the content itself. Various file types have "magic numbers" which you could use to identify the file - they're typically at the start of the file, and if you only have a limited set of file types to look for, this may well be a viable approach. It won't be able to identify all file types though.

As an example, the first four bytes of the image you've linked to are ff d8 ff e0. That reveals that actually it's not a jpeg image. As it happens, the server response also included a header of content-type: image/jpeg.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download