1

I am trying to transfer large files (5gb~50gb) on my server from to my external harddisk using windows application C#.

Code used to transfer the files:

    public void CopyFile(string source, string dest)
    {
        using (FileStream sourceStream = new FileStream(source, FileMode.Open))
        {
            byte[] buffer = new byte[64 * 1024]; // Change to suitable size after testing performance
            using (FileStream destStream = new FileStream(dest, FileMode.Create))
            {
                int i;
                while ((i = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    destStream.Write(buffer, 0, i);
                    //OnProgress(sourceStream.Position, sourceStream.Length);
                }
            }
        }
    }

But the problem with this code is that when the application runs, my application would just hang there (although file still transfers at a slow speed)

Is there a better method for copying large files from the remote server?

Bloopie Bloops
  • 1,216
  • 3
  • 21
  • 45

3 Answers3

1

You should do that operation in separate thread instead of the current main application thread because this is a blocking operation and your application will block until the transfer has finished. Have a look at the BackgroundWorker, it runs on a separate thread and you can send progress report back to the main thread which comes in handy and you could even implement progress bar.

Leo
  • 14,284
  • 2
  • 36
  • 54
0

If you're doing winforms, put this in your WHILE loop:

Application.DoEvents();

It won't block (freeze) any more.

Xavier J
  • 4,297
  • 1
  • 13
  • 25
  • Im using a for and foreach loop, it still hangs. Am i putting it in the wrong place? (I put it at the start of the loop) – Bloopie Bloops Jan 09 '14 at 01:32
  • while ((i = sourceStream.Read(buffer, 0, buffer.Length)) > 0) { Application.DoEvents(); //here!!! destStream.Write(buffer, 0, i); //OnProgress(sourceStream.Position, sourceStream.Length); } – Xavier J Jan 09 '14 at 01:33
0

Checkout BITS (Background Intelligent Transfer Service):

http://msdn.microsoft.com/en-us/library/aa363160(v=vs.85).aspx

rheitzman
  • 2,207
  • 2
  • 17
  • 34