[英]Empty array with BinaryReader on UploadedFile in c#
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". 如果我上传一个10个记录(257字节)的CSV文件,BinaryReader将用“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: 我还写了一个循环来逐步执行BinaryReader的ReadByte方法,在循环的第一次迭代中,我收到了以下异常:
Unable to read beyond the end of the stream 无法读取超出流的末尾
When I increase the CSV file to 200 hundred records, everything worked just fine. 当我将CSV文件增加到200个记录时,一切正常。
The question is then, Why does this happen on smaller files, and is there a workaround that allows the Binary read of smaller files. 问题是,为什么这会发生在较小的文件上,并且有一种解决方法允许二进制读取较小的文件。
不确定原因,但是当您在上传的流上使用BinaryReader时,需要明确设置起始位置。
b.BaseStream.Position = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.