Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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

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

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top