5

I am using c# .net compact framework 3.5 and I want to convert a video file to byte array so that I may upload it on the server.

In the similar manner I am doing the image uploading which is getting the success result.

HttpWebRequest request; 
request.ContentType = "image/jpeg";
request.ContentLength = byteArray.Length;
request.Method = "PUT";

imageToByteArray(img).CopyTo(byteArray, 0);
using (Stream requestStream = request.GetRequestStream())
{
  requestStream.Write(byteArray, 0, (int)Fs.Length);
  requestStream.Flush();
  requestStream.Close();
}


public byte[] imageToByteArray(Image imageIn)
{
  MemoryStream ms = new MemoryStream();
  imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
  return ms.ToArray();
}

How to do this for the video files?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Madhup Singh Yadav
  • 8,110
  • 7
  • 51
  • 84
  • 5
    You're loading the whole thing twice in memory. Better to open a FileStream and copy it to the request stream in chunks. see http://stackoverflow.com/questions/230128/best-way-to-copy-between-two-stream-instances-c and http://stackoverflow.com/questions/1493594/writing-a-stream-to-the-response-in-asp-net and http://stackoverflow.com/questions/674651/uploading-files-past-asp-net-request-length-limit –  Oct 20 '09 at 12:11

1 Answers1

12

You should copy the stream one block at a time instead of reading the entire file into an array. Otherwise, you'll use a potentially very large amount of memory as video files can grow quite big.

For example:

HttpWebRequest request; 
request.Method = "PUT";

using(Stream requestStream = request.GetRequestStream())
using(Stream video = File.OpenRead("Path")) {
    byte[] buffer = new byte[4096];

    while(true) {
        int bytesRead = video.Read(buffer, 0, buffer.Length);

        if (bytesRead == 0) break;
        requestStream.Write(buffer, 0, bytesRead);
    }
}
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964