开发者

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

开发者 https://www.devze.com 2023-04-11 02:09 出处:网络
I’m trying to have the program be able to cancel the copy. Therefore I can’t use Microsoft.VisualBasic.FileIO.FileSystem.CopyFile.

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


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.


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;
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消