Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a file with the ability to cancel the copy?

I’m trying to have the program be able to cancel the copy. Therefore I can’t use Microsoft.VisualBasic.FileIO.FileSystem.CopyFile.

There are some wrappers for CopyFileEx on the web such as here. However, I rather not use something I don’t understand, not wanting any unexpected results (or bugs). Is there a managed way to do this? Or perhaps a wrapper by MS (in something like Windows API CodePack)?

like image 875
ispiro Avatar asked Oct 06 '11 21:10

ispiro


2 Answers

Read the file in small chunks and write it out to the destination. Periodically check whether you've been asked to cancel and if you detect that, stop writing and close the files.

like image 157
Jon Cage Avatar answered Nov 15 '22 08:11

Jon Cage


Have you tried copying the stream in chunks and each time you check the chunk check if a cancel was set, or a cancellation token was registered?

For example you could do something like:

void CopyStream(Stream inputStream, Stream outputStream)
{
    var buffer = new byte[1024];

    int bytesRead;
    while((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        outputStream.Write(buffer, 0, bytesRead);
        if(cancelled){
           // cleanup

           return;
        }
    }
}
like image 22
devshorts Avatar answered Nov 15 '22 09:11

devshorts