0

In my project user can upload file up to 1GB. I want to copy that uploaded file stream data to second stream. If I use like this

int i;
while ( ( i = fuVideo.FileContent.ReadByte() ) != -1 )
{
  strm.WriteByte((byte)i);
}

then it is taking so much time.

If i try to do this by byte array then I need to add array size in long which is not valid.

If someone has better idea to do this then please let me know.

--

Hi Khepri thanks for your response. I tried Stream.Copy but it is taking so much time to copy one stream object to second.

I tried with 8.02Mb file and it took 3 to 4 minutes. The code i have added is

Stream fs = fuVideo.FileContent;  //fileInf.OpenRead();

Stream strm = ftp.GetRequestStream();
fs.CopyTo(strm);

If i am doing something wrong then please let me know.

Community
  • 1
  • 1
munish
  • 1
  • 2

2 Answers2

1

Is this .NET 4.0?

If so Stream.CopyTo is probably your best bet.

If not, and to give credit where credit is due, see the answer in this SO thread. If you're not .NET 4.0 make sure to read the comments in that thread as there are some alternative solutions (Async stream reading/writing) that may be worth investigating if performance is at an absolute premium which may be your case.

EDIT:

Based off the update, are you trying to copy the file to another remote destination? (Just guessing based on GetRequestStream() [GetRequestStream()]. The time is going to be the actual transfer of the file content to the destination. So in this case when you do fs.CopyTo(strm) it has to move those bytes from the source stream to the remote server. That's where the time is coming from. You're literally doing a file upload of a huge file. CopyTo will block your processing until it completes.

I'd recommend looking at spinning this kind of processing off to another task or at the least look at the asynchronous option I listed. You can't really avoid this taking a large period of time. You're constrained by file size and available upload bandwidth.

I verified that when working locally CopyTo is sub-second. I tested with a half gig file and a quick Stopwatch class returned a processing time of 800 millisecondss.

Community
  • 1
  • 1
Khepri
  • 9,547
  • 5
  • 45
  • 61
0

If you are not .NET 4.0 use this

    static void CopyTo(Stream fromStream, Stream destination, int bufferSize)
    {
      int num;
      byte[] buffer = new byte[bufferSize];
      while ((num = fromStream.Read(buffer, 0, buffer.Length)) != 0)
      {
         destination.Write(buffer, 0, num);
      }
   }
netcoder
  • 66,435
  • 19
  • 125
  • 142
Alois Kraus
  • 13,229
  • 1
  • 38
  • 64