views:

672

answers:

1

Hi,

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();
    }

Somebody having the idea how to do this for the video files?

+8  A: 

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