如何下载并保存图像两次
本文关键字:图像 两次 保存 下载 何下载 | 更新日期: 2023-09-27 18:27:46
这是我的代码(取自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);
}
}
}
现在,假设我想在path
和path + "'duplicates'";
上创建图像:最好的方法是什么?
回想不同路径的功能(所以我需要下载两次),或者我可以使用多个outputStream
吗?
System.Io.File.Copy(路径,重复路径)
只需在循环后复制文件,如下所示:
if (File.Exists(path))
File.Copy(path, duplicatePath);
您可以简单地使用多个输出流,如下所示:
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);
}