7

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

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
ispiro
  • 26,556
  • 38
  • 136
  • 291
  • 3
    However you do it, you're probably going to want to copy to a temp file, then move the temp file to the right place once the copy's done. That way you won't trash the (potentially existing) destination file when the copy's canceled. – cHao Oct 06 '11 at 21:29
  • 2
    Copying a file *correctly* is ridiculously difficult. Use Toub's code. – Hans Passant Oct 06 '11 at 21:42

2 Answers2

4

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.

Jon Cage
  • 36,366
  • 38
  • 137
  • 215
  • 1
    See [here](http://stackoverflow.com/questions/187768/can-i-show-file-copy-progress-using-fileinfo-copyto-in-net) in Coderer’s answer that, for example, my code wouldn’t take advantage of DMA. – ispiro Oct 06 '11 at 21:42
4

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;
        }
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
devshorts
  • 8,572
  • 4
  • 50
  • 73