Seb*_*ite 2 .net c# webclient image
我需要检索并将图像从网站保存到我的本地文件夹.图像类型在.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);
}
Run Code Online (Sandbox Code Playgroud)
但这会将文件'home_image'保存在没有扩展名的文件夹中.我的问题是你如何确定扩展名?有一个简单的方法吗?可以使用HTTP请求的Content-Type吗?如果是这样,你怎么做?
如果要使用a 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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果可以的话,我喜欢我的扩展名为3个字母....个人偏好.如果它不打扰你,你可以用以下代码替换整个switch语句:
saveloc += "." + fileType.Substring(fileType.IndexOf('/') + 1);
Run Code Online (Sandbox Code Playgroud)
使代码更整洁.
| 归档时间: |
|
| 查看次数: |
7470 次 |
| 最近记录: |