Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any difference in using File.Copy to move a file or to write a stream to the location?

Tags:

c#

io

asp.net-4.0

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);

like image 788
Poul K. Sørensen Avatar asked Feb 17 '23 15:02

Poul K. Sørensen


1 Answers

well, think about what happens when you start the download and override the existing file and then for some reason the download gets aborted, you'd be left with an broken file. however, downloading it first in another location and copying it to the target directory factors that problem out.

EDIT: okay, seeing the code now. if the file is already in the MemoryStream there's really no reason to write the file to a temp location and copy it over. you could just just do File.WriteAllBytes(destination,stream.ToArray());

like image 124
shriek Avatar answered Apr 28 '23 00:04

shriek