StreamReader ReadBlock 挂在二进制文件上
我有一个小类,它接受来自浏览器的包含文件上传的 POST。我使用 StreamReader 来读取它。我读取标题,然后当我到达正文时,我获取内容长度并创建一个该大小的数组,然后 stream.ReadBlock()
关于这一点:
char[] buffer = new char[contentLength];
stream.ReadBlock(buffer, 0, contentLength);
String body = new string(buffer);
当我运行它并发布一个文本文件时,它工作正常。但是,我尝试过 ZIP 文件和 MP3 文件,但都不起作用。它只是挂在 stream.ReadBlock()
调用上。
我首先在 Ubuntu 10.04 和 Mono 2.6.7 上尝试了这一点(我的 MonoDevelop 项目设置为使用 .net 3.5)。我刚刚通过在 VisualStudio 2010 和 .net 3.5 中运行相同的项目来验证 Windows7 上是否发生了同样的情况。我尝试过从 Firefox 和 Chrome 发帖。
任何人都知道为什么会发生这种情况?谢谢。
我还尝试使用 BinaryReader 而不是 StreamReader:
byte[] bytes = reader.ReadBytes(contentLength);
但无论现在如何,它最终都会挂在该调用上。是因为我使用 StreamReader 读取 POST 的标头,然后使用 BinaryReader 读取正文吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
StreamReader
用于文本数据。您不应该在二进制数据上使用它 - 您应该使用BinaryReader
或仅使用Stream
。StreamReader
is for text data. You shouldn't use it on binary data - you should useBinaryReader
or just theStream
.使用 StreamReader 不适用于二进制文件。它会做各种各样的文本编码工作,并且通常(可能)把事情搞砸。
一旦确定您正在使用的文件是二进制文件,您应该直接使用 Stream 对象来读取文件(的部分)。这样,您就不必处理弄乱内容的编码。
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.