如何下载和保存图像两次?

时间:2015-12-21 13:57:18

标签: c# .net image file download

这是我的代码(取自stackoverflow),用于下载,检查并在固定路径上存储图像:

private static void DownloadRemoteImageFile(string uri, string path)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    if ((response.StatusCode == HttpStatusCode.OK ||
        response.StatusCode == HttpStatusCode.Moved ||
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
    {
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(path))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
    }
}

现在,我要说我要在pathpath + "\duplicates\";上创建图片:最好的方法是什么?

回想一下具有不同路径的功能(所以我需要下载两次)或者我可以使用多个outputStream吗?

3 个答案:

答案 0 :(得分:5)

System.Io.File.Copy(path,duplicatePath)

答案 1 :(得分:3)

只需在你的循环之后复制文件:

  if (File.Exists(path))
    File.Copy(path, duplicatePath);

答案 2 :(得分:2)

您可以简单地使用多个outputStream:

using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(path))
using (Stream outputStream2 = File.OpenWrite(duplicatePath))
{
   byte[] buffer = new byte[4096];
   int bytesRead;
   do
   {
        bytesRead = inputStream.Read(buffer, 0, buffer.Length);
        outputStream.Write(buffer, 0, bytesRead);
        outputStream2.Write(buffer, 0, bytesRead);
    } while (bytesRead != 0);
}