我正在重构一些代码,有一个问题需要您的帮助。
原始代码将文件下载到流中。然后它将流写入临时目录中的文件,然后使用File.Copy覆盖生产目录中的现有文件。
与直接将流写入生产目录相比,将其先写入临时目录并使用File.Copy有什么好处吗?
一个原因可能是File.Copy比写入流更快,并减少了在写入文件时有人正在读取文件的机会。但是那真的会发生吗?还要考虑什么?我正在考虑将临时目录分离出来。
MemoryStream stream = new MemoryStream();
....Download and valiate stream....
using (Stream sourceFileStream = stream)
{
using (FileStream targetFileStream = new FileStream(tempPath, FileMode.CreateNew))
{
const int bufferSize = 8192;
byte[] buffer = new byte[bufferSize];
while (true)
{
int read = sourceFileStream.Read(buffer, 0, bufferSize);
targetFileStream.Write(buffer, 0, read);
if (read == 0)
break;
}
}
}
File.Copy(tempPath, destination, true);
与仅将流写入目标不同。
这只是我拥有的代码,我会正确使用类似于 sourceFileStream.CopyToAsync(TargetFileStream);
的东西。