栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从.NET / C#网站下载图像

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从.NET / C#网站下载图像

无需涉及任何图像类,您可以简单地调用

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
是图像。如果满足这些条件,则下载文件。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/568581.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号