views:

68

answers:

5

Hi,

I have a background worker running to copy a huge file (several GBs) and I'd like to know how to cancel the process in the middle of the copy. I can check CancellationPending property before the copy but don't know how to do it when copy is already in progress.

if (worker.CancellationPending) // check cancellation before copy 
{   
    e.Cancel = true;
}
else
{    
    File.Copy("sourceFile", "destinationFile"); // need to cancel this
}

Please advise, thanks!

A: 

As far as I know, background workers are best for running lots of little operations. I know it's messy, but you might want to look into creating a separate thread for your copy operation. That way, if you're in the middle of copying, you can just kill the thread. (I'm not sure what this would do to the copying, tho - I don't know if it would leave a temporary file behind using this method.)

Daniel Rasmussen
Killing the thread may be ineffective in this case. See [Thread.Abort() on MSDN](http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx): `If Abort is called on a managed thread while it is executing unmanaged code, a ThreadAbortException is not thrown until the thread returns to managed code.`
Humberto
Would you feel save if you'd know Windows Explorer was implemented that way? ...me neither.
Frank Bollack
@Frank: interesting fact...
Eddie
@ Eddie: That wasn't a fact, but merely a hint not to go into that direction, sorry for the confusion ;-)
Frank Bollack
+5  A: 

I'm not sure but I think that File.Copy is backed by the CopyFile function of the winapi that doesn't allow this feature.

You should point toward CopyFileEx that allows a callback method whenever a portion of the file has been copied.

Jack
OK - will try CopyFileEx, thx.
Eddie
+2  A: 

The only way I know of is to use CopyFileEx (kernel32)

Don
A: 

Copy the file in chunks. Between chunks, check if the operation has been cancelled.

This may smell like a wheel reinvention, but it's an option if you don't want to dllimport CopyFileEx.

Humberto
A: 

Instead of using File.Copy or any other copy function, you could also copy the file yourself (reading from a source stream, writing to a destination stream) in chunks. In the loop required to copy all chunks you could check whether to abort the operation and then perform necessary operations to abort the copy process.

Thorsten Dittmar