从网址复制图像文件到本地文件夹?

12
我有一个图片的网址,例如 "http://testsite.com/web/abc.jpg"。我想将该网址复制到我的本地文件夹"c:\images\"中; 同时,当我将该文件复制到文件夹中时,我需要将图片重命名为"c:\images\xyz.jpg"。
我们应该如何做呢?
4个回答

29

请求图片并保存,例如:

byte[] data;
using (WebClient client = new WebClient()) {
  data = client.DownloadData("http://testsite.com/web/abc.jpg");
}
File.WriteAllBytes(@"c:\images\xyz.jpg", data);

1
我喜欢这个答案,因为它不直接使用DownloadFile,而是给了一个比较数据的机会,然后再将其保存到文件中。 - MikeDub

10

你可以使用 WebClient

using (WebClient wc = new WebClient())
    wc.DownloadFile("http://testsite.com/web/abc.jpg", @"c:\images\xyz.jpg");

这假定你实际上对 C:\images 文件夹有写入权限。


2
请使用您有权限下载的URL进行尝试,否则您需要提供在目标服务器上有效的凭据给WebClient。 - BrokenGlass

3
那不太难。打开一个WebClient并获取数据,将它们保存在本地...
using ( WebClient webClient = new WebClient() ) 
{
   using (Stream stream = webClient.OpenRead(imgeUri))
   {
      using (Bitmap bitmap = new Bitmap(stream))
      {
         stream.Flush();
         stream.Close();
         bitmap.Save(saveto);
      }
   }
}

1
为什么要将JPG图像强制转换为位图? - Ryan Gates

1
string path = "~/image/"; 
string picture = "Your picture name with extention";
path = Path.Combine(Server.MapPath(path), picture);
using (WebClient wc = new WebClient())
                            {
wc.DownloadFile("http://testsite.com/web/abc.jpg", path);
                            }

它对我有效


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接