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?

1

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.