无需涉及任何图像类,您可以简单地调用
WebClient.DownloadFile:
string localFilename = @"c:localpathtofile.jpg";using(WebClient client = new WebClient()){ client.DownloadFile("http://www.example.com/image.jpg", localFilename);}更新
由于您将要检查文件是否存在并下载文件(如果存在),因此最好在同一请求中执行此操作。所以这是一个可以做到的方法:
private static void DownloadRemoteImageFile(string uri, string fileName){ HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Check that the remote file was found. The ContentType // check is performed since a request for a non-existent // image file might be redirected to a 404-page, which would // yield the StatusCode "OK", even though the image was not // found. if ((response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect) && response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase)) { // if the remote file was found, download oit using (Stream inputStream = response.GetResponseStream()) using (Stream outputStream = File.OpenWrite(fileName)) { byte[] buffer = new byte[4096]; int bytesRead; do { bytesRead = inputStream.Read(buffer, 0, buffer.Length); outputStream.Write(buffer, 0, bytesRead); } while (bytesRead != 0); } }}简言之,它使该文件,验证该响应代码是中的一个的请求
OK,
Moved或者
Redirect,也
使
ContentType是图像。如果满足这些条件,则下载文件。



