views:

83

answers:

2

I've got a little class that accepts a POST from a browser that contains file uploads. I'm using a StreamReader to read it in. I read the header, then when I get to the body, I get the content length and make an array of that size and then stream.ReadBlock() on that:

char[] buffer = new char[contentLength];
stream.ReadBlock(buffer, 0, contentLength);
String body = new string(buffer);

When I run this and POST a text file, it works fine. However, I've tried both a ZIP file and an MP3 file, and neither of those work. It just hangs on the stream.ReadBlock() call.

I tried this first on Ubuntu 10.04 with Mono 2.6.7 (my MonoDevelop Project is set to use .net 3.5). And I just verified the same thing happens on Windows7 by running the same project in VisualStudio 2010 and .net 3.5. I've tried posting from both Firefox, and Chrome.

Anyone have any clue why this would be happening? Thanks.

I also tried using a BinaryReader instead of a StreamReader:

byte[] bytes = reader.ReadBytes(contentLength);

but it ends up hanging on that call no matter what now. Is it because I use a StreamReader to read the header of the POST and then use a BinaryReader to read the body?

+3  A: 

StreamReader is for text data. You shouldn't use it on binary data - you should use BinaryReader or just the Stream.

Jon Skeet
I changed it to use a BinaryReader and it still hangs on reading.
Joel
@Joel: You need to update the question to show the new code.
Jon Skeet
I understand that the StreamReader is for text and the BinaryReader is for binaries. But does that explain why it would get stuck on reading? Wouldn't the textreader still read it in and just muck up the contents with encoding and such?
Joel
+1  A: 

Using a StreamReader is not appropriate for a binary file. It will do all sorts of text encoding stuff and generally (potentially) screw things up.

Once you've determined that the file you're working with is binary, you should use the Stream object directly to read (portions of) the file. That way, you won't have to deal with encodings messing up the contents.

Mark