C# 我收到错误无法读取超出流的末尾为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11979889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:56:08  来源:igfitidea点击:

Im getting error Unable to read beyond the end of the stream why?

c#

提问by Daniel Lip

The testing.res file is 240MB size. I want to read it. But im getting the error on this line:

testing.res 文件大小为 240MB。我想阅读它。但我在这条线上收到错误:

int v = br.ReadInt32();

EndOfStreamException Unable to read beyond the end of the stream

EndOfStreamException 无法读取超出流的末尾

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            R();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public void R()
        {
            using (var br = new System.IO.BinaryReader(File.Open(@"d:\testing.res", FileMode.Open)))
            {
                // 2.
                // Position and length variables.
                int pos = 0;
                // 2A.
                // Use BaseStream.
                int length = (int)br.BaseStream.Length;
                while (br.BaseStream.Position < length)
                {
                    // 3.
                    // Read integer.
                    int v = br.ReadInt32();
                    textBox1.Text = v.ToString();
                }

            }
        }
    }
}

The exception:

例外:

System.IO.EndOfStreamException was unhandled
  Message=Unable to read beyond the end of the stream.
  Source=mscorlib
  StackTrace:
       at System.IO.BinaryReader.FillBuffer(Int32 numBytes)
       at System.IO.BinaryReader.ReadInt32()
       at WindowsFormsApplication1.Form1.R() in D:\C-Sharp\BinaryReader\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 41
       at WindowsFormsApplication1.Form1..ctor() in D:\C-Sharp\BinaryReader\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 19
       at WindowsFormsApplication1.Program.Main() in D:\C-Sharp\BinaryReader\WindowsFormsApplication1\WindowsFormsApplication1\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

采纳答案by Alexei Levenkov

One reason your code could fail is if file contains extra bytes (i.e. 7 byte long file). Your code will trip on last 3 bytes.

您的代码可能失败的原因之一是文件包含额外的字节(即 7 字节长的文件)。您的代码将在最后 3 个字节上跳闸。

To fix - consider computing number of integers in advance and using forto read:

修复 - 考虑提前计算整数数量并for用于读取:

var count = br.BaseStream.Length / sizeof(int);
for (var i = 0; i < count; i++)
{
  int v = br.ReadInt32();
  textBox1.Text = v.ToString();
}

Note that this code will simply ignore last 1-3 bytes if they are there.

请注意,此代码将简单地忽略最后 1-3 个字节(如果它们在那里)。

回答by dasblinkenlight

You should use a more reliable way of figuring out when you are at the end of the stream, rather than rolling your own counter with sizeof(int). Your method may not be precise enough, and the fact that you are using an unsafe code for that is also not too good.

您应该使用更可靠的方法来确定何时到达流的末尾,而不是使用 滚动您自己的计数器sizeof(int)。您的方法可能不够精确,而且您为此使用了不安全的代码这一事实也不太好。

One way probe if you are at the end of the stream or not is to use the PeekCharmethod:

一种探测是否在流末尾的PeekChar方法是使用以下方法:

while (br.PeekChar() != -1)
{
    // 3.
    // Read integer.
    int v = br.ReadInt32();
    textBox1.Text = v.ToString();
}

A more common solution is to write the number of ints that you are saving in a binary file in front of the actual list of integers. This way you know when to stop without relying on the length or the position of the stream.

一个更常见的解决方案是int在实际整数列表的前面写下您在二进制文件中保存的s的数量。这样你就知道什么时候停止而不依赖于流的长度或位置。

回答by urvashi gautam

The binary reader is not pointing to the start of the stream.

二进制读取器未指向流的开头。

Use this code before reading the integer value:

在读取整数值之前使用此代码:

br.BaseStream.Seek(0, SeekOrigin.Begin);