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

别等时光非礼了梦想. 提交于 2020-02-02 03:08:50

问题


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

Thanks.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/7680640/how-to-copy-a-file-with-the-ability-to-cancel-the-copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!