Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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?

https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTw4P3HxyHR8wumE3lY3TOlGworijj2U2DawhY9wnmcPKnbmGHg

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

like image 437
CodeToad Avatar asked Jun 12 '14 06:06

CodeToad


1 Answers

If you trust the header information, this is possible to do using WebClient—you don't need to use HttpClient:

var webClient = new WebClient();
var result = webClient.DownloadData(url);
var contentType = webClient.ResponseHeaders["Content-Type"];

if (contentType != null && 
    contentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
    // it's probably an image
}
like image 153
David Sherret Avatar answered Oct 03 '22 02:10

David Sherret