简体   繁体   English

覆盖文件的最快方法是什么?

[英]What is the fastest way to overwrite a file?

I know this sounds very trivial, but I have a very specific reason for asking. 我知道这听起来很琐碎,但是我有一个非常具体的原因要问。

I'm reaching across a very crappy network to Mumbai, India. 我正在通过一个非常糟糕的网络到达印度孟买。 If I were local, I would simply run this code below: 如果我是本地人,则只需在下面运行以下代码:

                if (File.Exists(f2))
                {
                    File.Delete(f2);
                }

                File.Copy(f1, f2);

Of course, I have to test to see if the file exists first, because I can't just copy the file over the top of an existing file. 当然,我必须测试一下文件是否首先存在,因为我不能只是将文件复制到现有文件的顶部。 C# complains about that. C#对此抱怨。 Here's the problem.. The "Test to see if it exists first" takes 5 seconds alone. 这就是问题所在。“测试以首先发现它是否存在”仅花费5秒钟。 Then the delete takes about 3. And finally, the copy takes about 15. For a fifteen second copy, it ends up taking 23 seconds. 然后删除大约需要3个。最后,该副本大约需要15个。对于15秒钟的副本,最终需要23秒。

That's an increase of 8 seconds, or about 50% overhead, just to prevent a C# error. 为了防止C#错误,这增加了8秒或大约50%的开销。

Is there any way to say 有什么话要说

File.Copy(f1, f2, Just_do_it_damnit)

... without all of the "does it exist" overhead? ...没有所有的“存在”开销?

是的,您可以使用File.Copy(f1, f2, true)覆盖目标文件。

当然,仅使用此功能有什么问题?

File.Copy(f1,f2,true);

The answer is in the question. 答案就在问题上。

File.Copy(f1, f2, true);

See Microsoft's page about it: 请参阅Microsoft的页面:

http://msdn.microsoft.com/en-us/library/aa328774%28v=VS.71%29.aspx http://msdn.microsoft.com/zh-cn/library/aa328774%28v=VS.71%29.aspx

File.Copy has third parameter -- a boolean flag which specifies if should overwrite if the file already exists. File.Copy具有第三个参数-一个布尔标志,用于指定如果文件已经存在,是否应该覆盖。 So I would think File.Copy(f1, f2, true) so do what you want. 因此,我认为File.Copy(f1,f2,true)可以满足您的需求。

http://msdn.microsoft.com/en-us/library/9706cfs5(v=VS.80).aspx http://msdn.microsoft.com/zh-CN/library/9706cfs5(v=VS.80).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM