Empty array with BinaryReader on UploadedFile in c#
Asked Answered
S

1

9

Assume the following code:

Stream file = files[0].InputStream;

var FileLen = files[0].ContentLength;

var b = new BinaryReader(file);
var bytes = b.ReadBytes(FileLen);

If I upload a CSV file that is 10 records ( 257 bytes ), the BinaryReader fills the array of bytes with "0".

I also wrote a loop to step through the ReadByte Method of the BinaryReader and in the first iteration of the loop, I received the following exception:

Unable to read beyond the end of the stream

When I increase the CSV file to 200 hundred records, everything worked just fine.

The question is then, Why does this happen on smaller files, and is there a workaround that allows the Binary read of smaller files.

Swanky answered 3/2, 2011 at 7:57 Comment(5)
Try b.BaseStream.Position = 0; before calling ReadBytesPiglet
@Piglet I would expect a file upload to start at origin...Behold
Bizarre - and if you check with Fiddler etc, is there a payload?Behold
Yes, there is a payload, I am able to load the payload into a streamreader and pull the first line, I am sure I could pull all info that way. I would like to store binary in the DB instead of the string form though.Swanky
@Adeel, you were exactly right, after checking everything over and over again, it was the BaseStream.position that was the problem.Swanky
S
24

Not sure why, but when you are using BinaryReader on an uploaded stream, the start position needs to be explicitly set.

b.BaseStream.Position = 0;
Swanky answered 7/2, 2011 at 21:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.