What is the fastest way to overwrite a file?
I k开发者_StackOverflow社区now 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?
Yes, you can use File.Copy(f1, f2, true)
to overwrite the destination file.
Sure, what's wrong with just using this?
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
精彩评论