这是我的代码(取自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
吗?
答案 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);
}