I am refactoring some code an have a question that i could use a few comments on.
The original code download a file to a stream. Then it writes the stream to a File in a temp directory before using File.Copy to overwrite an existing file in the production directory.
Are there any benefits from writing it to the temp dir first and using the File.Copy in contrast to just writing the stream to the production directory right away?
One reason could be that the File.Copy is faster then writing a stream, and reducing the chance that someone is reading the file while its being written. But can that even happen? What else should I have in mind. I am considering factoring out the temp directory.
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);
in contrast to just writing the stream to destination.
This is just the code I had, i would properly use something like sourceFileStream.CopyToAsync(TargetFileStream);