Search code examples
c#streamcopyfilestreamresume

C# - Copying files and resume support


Hi Does anyone have workable sample code that copy files and support resuming them if there are the source has been disconnected?

In this example I am copying videos files. If the source is disconnected ie usb was unplugged, how can I support resuming them again? I have tried some code on stackoverflow, but after resuming, the video files seem to be corrupted. Is FileStream the best solution for video transfers/resume?

Any other pointers or tips are welcome.

private void CreateNewCopyTo(FileStream source, FileStream dest) {
  int size = (source.CanSeek) ? Math.Min((int)(source.Length - source.Position), 0x2000) : 0x2000;
  byte[] buffer = new byte[size];
  int read;
  long fileLength = source.Length;
  while ((read = source.Read(buffer, 0, buffer.Length)) > 0) {
    dest.Write(buffer, 0, read);
    dest.Close();
    dest = new FileStream(dest.Name, FileMode.Append, FileAccess.Write);
  }
  dest.Close();
}

private void ResumeCopyTo(FileStream source, FileStream dest) {
  int size = (source.CanSeek) ? Math.Min((int)(source.Length - source.Position), 0x2000) : 0x2000;
  byte[] buffer = new byte[size];
  long TempPos = source.Position;
  while (true) {
    int read = source.Read(buffer, 0, buffer.Length);
    if (read <= 0)
      return;
    dest.Write(buffer, 0, read);
    dest.Close();
    dest = new FileStream(dest.Name, FileMode.Append, FileAccess.Write);
  }
}

Solution

  • Try to insert source.Seek(dest.Length, SeekOrigin.Begin); as first line in ResumeCopyTo method.