Using a WebClient to save an image with the appropriate extension

浪子不回头ぞ 提交于 2019-12-06 10:52:05

If you want to use a WebClient, then you have to extract the header information from WebClient.ResponseHeaders. You'll have to store it as a byte array first, and then save the file after getting your file information.

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);
    }
}

I like my extensions to be 3 letters long if they can.... personal preference. If it doesn't bother you, you can replace the entire switch statement with:

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

Makes the code a little neater.

Try something like this

 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();

Then save the stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!