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

I am trying so that the program can cancel the copy. Therefore I can not use Microsoft.VisualBasic.FileIO.FileSystem.CopyFile . There are several wrappers for CopyFileEx on the Internet, for example here . However, I prefer not to use what I do not understand, not wanting any unexpected results (or errors). Is there any way to do this? Or maybe the MS shell (something like the Windows API CodePack)?

Thanks.

+6
source share
2 answers

Read the file in small pieces and write it to your destination. Periodically check if you were asked to cancel, and if you find this, stop recording and close the files.

+3
source

Did you try to copy the stream in pieces, and each time you check the chunk, check if a cancellation has been set, or a cancellation token has been registered?

For example, you can 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; } } } 
+4
source

Source: https://habr.com/ru/post/898797/


All Articles