Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Video to byte Array in C#?

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?

like image 719
Madhup Singh Yadav Avatar asked Oct 20 '09 12:10

Madhup Singh Yadav


1 Answers

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);
    }
}
like image 126
SLaks Avatar answered Oct 21 '22 05:10

SLaks