164

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œur
  • 37,241
  • 25
  • 195
  • 267
frosty
  • 5,330
  • 18
  • 85
  • 122
  • how are we posting the file in another .aspx page? – shivi Jun 23 '15 at 01:42
  • Doesn't this line **file.InputStream.Read(buffer, 0, file.ContentLength);** fill the buffer with bytes from the input stream? Why should we use **BinaryReader.ReadBytes(...)** as mentioned by @Wolfwyrd in the answer below? Won't **ImageElement.FromBinary(buffer);** fix the problem? – Srinidhi Shankar Jun 20 '17 at 06:00

6 Answers6

309

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);
}
Robert MacLean
  • 38,975
  • 25
  • 98
  • 152
Wolfwyrd
  • 15,716
  • 5
  • 47
  • 67
  • 1
    As mentioned below by jeff, b.ReadBytes(file.InputStream.Length); should be byte[] binData = b.ReadBytes(file.ContentLength); as .Length is a long whereas ReadBytes expects an int. – Spongeboy Dec 17 '09 at 04:13
  • Remember to close the BinaryReader. – Chris Jun 01 '10 at 17:00
  • 33
    Binary reader doesn't have to be closed, because there is a using that is automaticaly closing the reader on disposal – BeardinaSuit Oct 28 '11 at 13:14
  • 1
    Any idea on why this wouldn't work for a .docx file? http://stackoverflow.com/questions/19232932/how-do-i-get-a-byte-array-from-httpinputstream-for-a-docx-file – wilsjd Oct 07 '13 at 19:42
28
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);
Andre Figueiredo
  • 12,930
  • 8
  • 48
  • 74
15

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;
tinamou
  • 2,282
  • 3
  • 24
  • 28
3

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

ImageElement image = ImageElement.FromBinary(buffer);
devio
  • 36,858
  • 7
  • 80
  • 143
2

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

László Papp
  • 51,870
  • 39
  • 111
  • 135
xpfans
  • 81
  • 3
2

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();
Jodda
  • 25
  • 4