使用WebClient保存具有适当扩展名的图像

我需要检索并将图像从网站保存到我的本地文件夹。 图像类型在.png,.jpg和.gif之间变化

我试过用过

string url = @"http://redsox.tcs.auckland.ac.nz/CSS/CSService.svc/"; string saveLoc = @"/project1/home_image"; using (var wc = new WebClient()) { wc.DownloadFile(url, saveLoc); } 

但这会将文件’home_image’保存在没有扩展名的文件夹中。 我的问题是你如何确定扩展名? 有一个简单的方法吗? 可以使用HTTP请求的Content-Type吗? 如果是这样,你怎么做?

如果要使用WebClient ,则必须从WebClient.ResponseHeaders提取标头信息。 您必须先将其存储为字节数组,然后在获取文件信息后保存文件。

 string url = @"http://redsox.tcs.auckland.ac.nz/CSS/CSService.svc/"; string saveLoc = @"/project1/home_image"; using (WebClient wc = new WebClient()) { byte[] fileBytes = wc.DownloadData(url); string fileType = wc.ResponseHeaders[HttpResponseHeader.ContentType]; if (fileType != null) { switch (fileType) { case "image/jpeg": saveloc += ".jpg"; break; case "image/gif": saveloc += ".gif"; break; case "image/png": saveloc += ".png"; break; default: break; } System.IO.File.WriteAllBytes(saveloc, fileBytes); } } 

如果可以的话,我喜欢我的扩展名为3个字母….个人偏好。 如果它不打扰你,你可以用以下代码替换整个switch语句:

 saveloc += "." + fileType.Substring(fileType.IndexOf('/') + 1); 

使代码更整洁。

尝试这样的事情

  HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Your URL"); request.Method = "GET"; var response = request.GetResponse(); var contenttype = response.Headers["Content-Type"]; //Get the content type and extract the extension. var stream = response.GetResponseStream(); 

然后保存流