Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write Binary File

Tags:

c#

.net

binary

I am reading data from an IPhone App that uses http POST to transfer the image to the Server I can read this into a an binary and it does write to a file (See below) the issue I have is when I open the image it fails.

You can see the code from the Iphone on this post: asp http POST Read Data

Code:

byte[] buffer = new byte[Request.ContentLength];
using (BinaryReader br = new BinaryReader(Request.InputStream))
    br.Read(buffer, 0, buffer.Length);

string fileName = @"C:\test\test.jpg";
FileStream fs = new FileStream(fileName, FileMode.Create, 
    FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buffer);
bw.Close();

The image Content-Type is application/octet-stream

Can anyone shine any light onto this please.

like image 385
MartGriff Avatar asked Nov 27 '25 21:11

MartGriff


1 Answers

Perhaps the Request.ContentLength was not set correctly? I know from bitter experience that it's not always safe to trust it. :-(

You can read the stream without knowing the length in advance like this:

const int bufferSize = 1024 * 64; // pick any reasonable buffer size
List<byte> buffer = new List<byte>();
using(Stream stream = new BufferedStream(request.InputStream, bufferSize)) {
    int value;
    while((value = stream.ReadByte()) != -1) {
        buffer.Add((byte) value);
    }
}
like image 159
Christian Hayter Avatar answered Nov 30 '25 11:11

Christian Hayter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!