简体   繁体   中英

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. Here's the problem.. The "Test to see if it exists first" takes 5 seconds alone. Then the delete takes about 3. And finally, the copy takes about 15. For a fifteen second copy, it ends up taking 23 seconds.

That's an increase of 8 seconds, or about 50% overhead, just to prevent a C# error.

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

You mean

File.Copy(f1, f2, True)

See http://msdn.microsoft.com/en-us/library/9706cfs5.aspx

The answer is in the question.

File.Copy(f1, f2, true);

See Microsoft's page about it:

http://msdn.microsoft.com/en-us/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. So I would think File.Copy(f1, f2, true) so do what you want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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