开发者

How to download a file without extension in C#

Okay so I want to download a file from a website, but the file is lacking an extension. (it's an image file, I know this much, but the link does not provide the actual extension)

When I use webrequest, or webclient to download the file I get a "404 file not found" exception.

        WebClient wc = new WebClient();

        Stream strm = wc.DownloadFile("http://some_site.some_d开发者_运维问答omain/some_image.","C:/some_directory/save_name.some_extention");

Notice the lack of extention at the end of the URL. The site in question displays the image fine in a webbrowser, but when viewing just the image there is no extension and thus it's treated an unknown file (not showing an image).

So simply put: how do I download a file if there is no extention specified?

Thanks in advance!


So you're trying to determine what extension to give the file after downloading? If the URL doesn't have one you would have to inspect the actual data of the file.

You might be able to inspect the beginning of the file and see if it matches known valid file types. For instance, PNGs seem to have 'PNG' as bytes 2-4 (at least in the ones I've inspected). By looking at that data you should be able to determine the format with a fairly high accuracy.


This would be my best suggestion, if this doesn't work I don't know how to solve you problem...

List<string> fileExtensions = new List<string>(){"png","gif","bmp","jpg"}// other known image file extensions here...

WebClient wc = new WebClient();
foreach(var extension in fileExtensions)
{
  try
  {     wc.DownloadFile("http://some_site.some_domain/some_image."+extension,"C:/some_directory/save_name."+extension);
   break;
  }
  catch {}
}

This would just be a work around, I guess... Not a real solution...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜