How to create byte array from HttpPostedFile

C#Arrays

C# Problem Overview


I'm using an image component that has a FromBinary method. Wondering how do I convert my input stream into a byte array

HttpPostedFile file = context.Request.Files[0];
byte[] buffer = new byte[file.ContentLength];
file.InputStream.Read(buffer, 0, file.ContentLength);

ImageElement image = ImageElement.FromBinary(byteArray);

C# Solutions


Solution 1 - C#

Use a BinaryReader object to return a byte array from the stream like:

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}

Solution 2 - C#

BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);

line 2 should be replaced with

byte[] binData = b.ReadBytes(file.ContentLength);

Solution 3 - C#

It won't work if your file InputStream.Position is set to the end of the stream. My additional lines:

Stream stream = file.InputStream;
stream.Position = 0;

Solution 4 - C#

in your question, both buffer and byteArray seem to be byte[]. So:

ImageElement image = ImageElement.FromBinary(buffer);

Solution 5 - C#

before stream.copyto, you must reset stream.position to 0; then it works fine.

Solution 6 - C#

For images if your using Web Pages v2 use the WebImage Class

var webImage = new System.Web.Helpers.WebImage(Request.Files[0].InputStream);
byte[] imgByteArray = webImage.GetBytes();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfrostyView Question on Stackoverflow
Solution 1 - C#WolfwyrdView Answer on Stackoverflow
Solution 2 - C#jeffView Answer on Stackoverflow
Solution 3 - C#tinamouView Answer on Stackoverflow
Solution 4 - C#devioView Answer on Stackoverflow
Solution 5 - C#xpfansView Answer on Stackoverflow
Solution 6 - C#JoddaView Answer on Stackoverflow