是否有使用File.Copy移动一个文件或写一个流的位置有什么区别? [英] Are there any difference in using File.Copy to move a file or to write a stream to the location?

查看:244
本文介绍了是否有使用File.Copy移动一个文件或写一个流的位置有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我重构了一些代码有,我可以上使用了一些评论的问题。

I am refactoring some code an have a question that i could use a few comments on.

原代码下载文件到流。然后,它使用File.Copy覆盖生产目录中的现有文件之前写入流中的一个临时目录中的文件。

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.

有没有从中写入任何好处在临时目录第一,相比之下使用File.Copy只写入流的生产目录,对吗?

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?

其中一个原因可能是因为File.Copy更快然后写一个流,并减少有人正在读取文件,而其被写入的机会。但即使发生?我应该记住什么。 。我正在考虑分解出temp目录

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.

这仅仅是代码我有,我会正确使用像 sourceFileStream.CopyToAsync(TargetFileStream);

This is just the code I had, i would properly use something like sourceFileStream.CopyToAsync(TargetFileStream);

推荐答案

File.Copy 简单封装流的使用等没有区别的。

File.Copy simply encapsulates the usage of streams, etc. No difference at all.

这篇关于是否有使用File.Copy移动一个文件或写一个流的位置有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆