简体   繁体   中英

Does File.Copy return only after file is copied?

I haven't been able to find an answer to this question, and haven't been sure how to test it.

If I have the following two lines;

TextWriter tw = new StreamWriter(txtPath,true);

File.Copy(OriginalPath, DestinationPath));

tw.WriteLine("blah");

Does the 3rd line wait until the File.Copy is completely done, or could the 3rd line be starting while the File.Copy is still being ran?

Yes, it will wait, as File.Copy() is a synchronous method call / file copy operation.

You can download Visual Studio 2013 Express Edition for Windows Desktop for free, to test out this C# code. Download link

Create a new console application project in Visual Studio, and run your code inside the Main() method declaration. If you copy a 5-10GB file with your code, you will notice that the call to the Copy() method takes some time to return.

I'm not clear on why your asking this, but File.Copy is a "synchronous" method--so it won't return until the OS thinks it has copied the file. But, beware, because depending on the drive where the copy is being performed, the write might be cached and not fully written to disk. Subsequent operations on that disk will take that into account (eg if you then tried to copy the first destination to a new one, that would work); but if the disk loses power after File.Copy returns, all the data may not have been written to disk . This is a particular problem with some SSD drives.

The framework is generally quite well designed. If a particular method wasn't going to have completed its work by the time it returns, it would return you something by which you could determine when the operation had completed (ie Task , Task<T> or IAsyncResult )

File.Copy is a void method returning nothing, so the expectation is that it has completed its work when it returns.

According to ILSpy , the File.Copy method internally calls the Win32 CopyFile function at some point which in turn is a synchronous function.

So in my opinion, it is completely synchron, not asynchron. Thus, your 3rd line is called after the file is fully copied.

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