Меню

Ошибка времени выполнения unable to read beyond the end of the stream

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

int v = br.ReadInt32();

EndOfStreamException
Unable to read beyond the end of the stream

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-SharpBinaryReaderWindowsFormsApplication1WindowsFormsApplication1Form1.cs:line 41
       at WindowsFormsApplication1.Form1..ctor() in D:C-SharpBinaryReaderWindowsFormsApplication1WindowsFormsApplication1Form1.cs:line 19
       at WindowsFormsApplication1.Program.Main() in D:C-SharpBinaryReaderWindowsFormsApplication1WindowsFormsApplication1Program.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: 

  • Remove From My Forums
  • Question

  • private void button1_Click(object sender, EventArgs e)
            {
                fs = new FileStream(Directory.GetCurrentDirectory() + "\FTask.dat", FileMode.Append);
                BinaryWriter writer = new BinaryWriter(fs);

                writer.Write(txtName.Text);
                writer.Write(txtNickName.Text);

                if (rdoMale.Checked == true)
                    writer.Write("Male");
                else
                    writer.Write("Female");

                writer.Write(txtAge.Text);
                writer.Write(dtpBirthDate.Value.ToShortDateString());
                writer.Write(txtEmail.Text);
                writer.Write(txtPhone.Text);
                writer.Write(cbxStatus.SelectedItem.ToString());
                writer.Close();

    }

    private void frmOrganizer_Load(object sender, EventArgs e) { fs = new FileStream(Directory.GetCurrentDirectory() + "\FTask.dat", FileMode.Open); BinaryReader reader = new BinaryReader(fs); while (fs.Position < fs.Length) { txtName.Text = reader.ReadString(); txtNickName.Text = reader.ReadString(); if (reader.ReadBoolean() == true) rdoMale.Checked = true; else rdoFemale.Checked = true; txtAge.Text = reader.ReadString(); dtpBirthDate.Value = Convert.ToDateTime(reader.ReadString()); txtEmail.Text = reader.ReadString(); txtPhone.Text = reader.ReadString(); cbxStatus.SelectedItem = reader.ReadString(); } reader.Close(); }

    • Edited by

      Saturday, June 15, 2013 3:32 PM

Answers

  • I do not think you have to use a while loop, but you must write and read the exact kind of data in correct order.

    For writing try this:

    writer.Write(txtName.Text);
    writer.Write(txtNickName.Text);
    writer.Write(rdoMale.Checked);
    writer.Write(txtAge.Text);
    writer.Write(dtpBirthDate.Value.ToBinary());
    writer.Write(txtEmail.Text);
    writer.Write(txtPhone.Text);
    writer.Write(cbxStatus.SelectedItem.ToString());

    For reading, remove the while line (or replace with if, which checks that the file is not empty) and try this:

    txtName.Text = reader.ReadString();
    txtNickName.Text = reader.ReadString();
    rdoMale.Checked = reader.ReadBoolean();
    txtAge.Text = reader.ReadString();
    dtpBirthDate.Value = DateTime.FromBinary(reader.ReadInt64());
    txtEmail.Text = reader.ReadString();
    txtPhone.Text = reader.ReadString();
    cbxStatus.SelectedItem = reader.ReadString();

    (If cbxStatus does not contain strings, then it has to be saved in different manner. Show some details about
    cbxStatus items if the last line does not work).

    • Edited by
      Viorel_MVP
      Sunday, June 16, 2013 7:40 AM
    • Proposed as answer by
      Mike Feng
      Monday, June 17, 2013 1:27 AM
    • Marked as answer by
      Mike Feng
      Monday, June 24, 2013 2:30 PM

50 / 37 / 9

Регистрация: 25.06.2014

Сообщений: 406

1

08.06.2015, 21:27. Показов 3045. Ответов 5


Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
uses crt;
label 1,2;
var f1:file of integer;
x,i,i1,i2,n:integer;
begin
assign(f1, 'g:131.txt');
Rewrite(f1);
randomize;
Writeln('Сколько будет чисел?');
Readln(n);
for i:=1 to n do begin
//x:=random(100)-10;
x:=random(18001)-9000;
write(f1,x);
write(x,' ');
end;
for i:=1 to n do begin
read(f1,x);
if not(odd(x)) then begin
i1:=i;
break;
end;
end;
for i:=n downto 1 do begin
read(f1,x);
if not(odd(x)) then begin
i2:=i2+1;
break;
end
else
i2:=i2+1;
end;
seek(f1,i1);
write(f1,i2);
seek(f1,i2);
write(f1,i1); 
While not Eof(f1) do begin
Read(f1, x);
Write(x,' ');
end;
close(f1);
end.

При попытки вывода выдает ошибку: «unable to read beyond the end of the stream».

Все, кроме этого компилируется

Pascal
1
2
3
4
5
6
While not Eof(f1) do begin
Read(f1, x);
Write(x,' ');
end;
close(f1);
end.

Добавлено через 13 минут
Сори, проблема не в выводе. Проблема заключается в циклах:

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for i:=1 to n do begin
read(f1,x);
if not(odd(x)) then begin
i1:=i;
break;
end;
end;
for i:=n downto 1 do begin
read(f1,x);
if not(odd(x)) then begin
i2:=i2+1;
break;
end
else
i2:=i2+1;
end;

но что в них не так?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Узнай цену своей работы

Формулировка задачи:

Ошибка на 11-ой строке. Обясните пожалуйста чём причина.

Код к задаче: «Ошибка времени выполнения unable to read beyond the end of stream»

textual

Листинг программы

assign(i,'C:Seva`s gamesa');
rewrite(i);
close(i);

Полезно ли:

12   голосов , оценка 4.000 из 5

Похожие ответы

  1. Не работает if r = 2 then begin
  2. Выдает ошибку
  3. Ошибка в готовой программе
  4. Ошибка в построении
  5. Ошибка при вводе значений массива
  6. Вывод сообщения если строка пустая после выполнения алгоритма
  7. Ошибка в разделе type
  8. Ошибка в программе «встречено ‘.’, а ожидвлось «
  9. Ошибка в типизированном файле
  10. Добавить меню выбора режима шифрование, расшифровка. Проверку цифр ( если отрицательное число-ошибка)
  11. Выяснить, предшествует ли время t времени t1

Same here after updating to 2.105.923.0
But after the EndOfStreamException I also have a ErrorException
«Evaluation resulted in a stack overflow and cannot continue.»

DataMashup.Trace Warning: 24579 : {"Start":"2022-05-30T22:57:07.1510658Z","Action":"ErrorTranslatingMessenger/Read","Exception":"Exception:
ExceptionType: System.IO.EndOfStreamException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message: Unable to read beyond the end of the stream.
StackTrace:
   at System.IO.__Error.EndOfFile()
   at System.IO.BinaryReader.FillBuffer(Int32 numBytes)
   at System.IO.BinaryReader.ReadInt32()
   at Microsoft.Mashup.Evaluator.MessageSerializer.Deserialize(BinaryReader reader)
   at Microsoft.Mashup.Evaluator.StreamMessenger.Read()
   at Microsoft.Mashup.Evaluator.ErrorTranslatingMessenger.MessageChannel.Read()
","ProductVersion":"2.105.923.0 (22.05)","ActivityId":"00000000-0000-0000-0000-000000000000","Process":"msmdsrv","Pid":3876,"Tid":13,"Duration":"00:00:00.0261973"}

DataMashup.Trace Warning: 24579 : {"Start":"2022-05-30T22:57:07.1772767Z","Action":"ErrorTranslatingMessenger/Read","Exception":"Exception:
ExceptionType: Microsoft.Mashup.Evaluator.Interface.ErrorException, Microsoft.MashupEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
Message: Evaluation resulted in a stack overflow and cannot continue.
StackTrace:
   at Microsoft.Mashup.Evaluator.ErrorTranslatingMessenger.MessageChannel.Read()
   at Microsoft.Mashup.Evaluator.ErrorTranslatingMessenger.MessageChannel.Read()
","ProductVersion":"2.105.923.0 (22.05)","ActivityId":"00000000-0000-0000-0000-000000000000","Process":"msmdsrv","Pid":3876,"Tid":13,"Duration":"00:00:00.0009396"}

DataMashup.Trace Warning: 24579 : {"Start":"2022-05-30T22:57:07.1798885Z","Action":"RemoteDocumentEvaluator/RemoteEvaluation/TranslateCancelExceptions","HostProcessId":"3876","identity":null,"evaluationID":"1","cancelled":"False","Exception":"Exception:
ExceptionType: Microsoft.Mashup.Evaluator.Interface.ErrorException, Microsoft.MashupEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
Message: Evaluation resulted in a stack overflow and cannot continue.
StackTrace:
   at Microsoft.Mashup.Evaluator.ErrorTranslatingMessenger.MessageChannel.Read()
   at Microsoft.Mashup.Evaluator.ErrorTranslatingMessenger.MessageChannel.Read()
   at Microsoft.Mashup.Evaluator.ChannelMessenger.Read(MessageChannel channel)
   at Microsoft.Mashup.Evaluator.ChannelMessenger.MessageChannel.Read()
   at Microsoft.Mashup.Evaluator.Interface.IMessageChannelExtensions.WaitFor[T](IMessageChannel channel)
   at Microsoft.Mashup.Evaluator.MessageBasedInputStream.ReadNextChunkAndCheckIfClosed()
   at Microsoft.Mashup.Evaluator.MessageBasedInputStream.ReadNextChunk()
","ProductVersion":"2.105.923.0 (22.05)","ActivityId":"c6a66d1e-8ac3-4e4c-8c83-13384f19af9c","Process":"msmdsrv","Pid":3876,"Tid":13,"Duration":"00:00:00.0000616"}

And after that impossible to cancel the refresh, I have to kill the process.
MarcVL_0-1653952981408.png

Я получаю ошибку, неспособную читать за пределами конца потока, почему?

тестирование.файл res имеет размер 240MB.
Я хочу его прочесть. Но я получаю ошибку на этой строке:

int v = br.ReadInt32();

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();
                }

            }
        }
    }
}

исключение:

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-SharpBinaryReaderWindowsFormsApplication1WindowsFormsApplication1Form1.cs:line 41
       at WindowsFormsApplication1.Form1..ctor() in D:C-SharpBinaryReaderWindowsFormsApplication1WindowsFormsApplication1Form1.cs:line 19
       at WindowsFormsApplication1.Program.Main() in D:C-SharpBinaryReaderWindowsFormsApplication1WindowsFormsApplication1Program.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: 

2 ответов


одна из причин сбоя кода — если файл содержит дополнительные байты (т. е. файл длиной 7 байт). Ваш код будет срабатывать на последних 3 байтах.

чтобы исправить-рассмотрим вычисление числа целых чисел заранее и с помощью for читать:

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

обратите внимание, что этот код будет просто игнорировать последние 1-3 байта, если они там есть.


вы должны использовать более надежный способ выяснить, когда вы находитесь в конце потока, а не катить свой собственный счетчик с sizeof(int). Ваш метод может быть недостаточно точной, и тот факт, что вы используете небезопасный код, что тоже не слишком хорошо.

один из способов зонда, если вы находитесь в конце потока или нет, чтобы использовать PeekChar способ:

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

более распространенным решением является запись числа ints, которые вы сохраняете в двоичном файле перед фактическим списком целых чисел. Таким образом, вы знаете, когда остановиться, не полагаясь на длину или положение потока.



Recommended Answers

One thing that looks different is line 46:
d.Age = (int)r.ReadInt64();

You are reading a 64 bit integer but you have created it on line 35 as a 32 bit integer (int).

Change to
d.Age = (int)r.ReadInt32();

Jump to Post

hmm… Did you save the data into a file in the same order then you are retreiving them back out?

the point is that you cannot just simply asign some binary data to something. You have to get the data into the text in some order, and then retreive …

Jump to Post

All 8 Replies

Member Avatar

12 Years Ago

One thing that looks different is line 46:
d.Age = (int)r.ReadInt64();

You are reading a 64 bit integer but you have created it on line 35 as a 32 bit integer (int).

Change to
d.Age = (int)r.ReadInt32();

Member Avatar

12 Years Ago

Thanks single blade , it works now. but why wont the number show up clearly in the text?

why am i being shown some weird square after the file is produced??

Member Avatar

12 Years Ago

Thanks single blade , it works now. but why wont the number show up clearly in the text?

why am i being shown some weird square after the file is produced??

Member Avatar

12 Years Ago

btw, why do you use a BinaryRader class, becuase you only read from a text file?
Why you dont use StreamReader instead, and you wont even need to convert byte into string, something?

An idea.
Mitja

Member Avatar

12 Years Ago

i know the method of StreamReader. i wanted to investigate how to do it with Binary,
why does it refuse to translate it to an int..?

Member Avatar

12 Years Ago

hmm… Did you save the data into a file in the same order then you are retreiving them back out?

the point is that you cannot just simply asign some binary data to something. You have to get the data into the text in some order, and then retreive them back in the same way:EXAMPLE!

If this is not enough its better to take a look into some other example, that you will learn how to use bytes and converted them back to the characters (strings, integers,…).

Give it some time and go through all the code slowely:
http://msdn.microsoft.com/es-es/library/system.io.binaryreader.aspx

Edited

12 Years Ago
by Mitja Bonca because:

adding some info

Member Avatar

12 Years Ago

<quote>why am i being shown some weird square after the file is produced??</quote>

The square usually means some non visual output like a new line character or tab or something similar.

Check your file and make sure there is nothing in it but the age.

Member Avatar

12 Years Ago

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;



namespace ConsoleApplication1
{
    class Program
    { 
        static void Main(string[] args)
        {
            string filename = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\test.txt";

            Person person = new Person { Name = "Ana", Age = 25, Height = 1.70 };
            Console.WriteLine(person);
            BinaryWriter bw = new BinaryWriter(File.Create(filename));
            person.Save(bw);
            bw.Close();
            person = null;
            Console.WriteLine("==========================");
            BinaryReader br = new BinaryReader(File.OpenRead(filename));
            person=  Person.Load(br);
            Console.WriteLine(person);
        }
       
    }
}
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public double Height { get; set; }
    public Person Yadid { get; set; }

    public override string ToString()
    {
        return string.Format("Name: {0} Age: {1} Height: {2}", Name, Age, Height);
    }
    public void Save(BinaryWriter bw)
    {
        bw.Write(Name);
        bw.Write(Age);
        bw.Write(Height);
    //    if(Yadid!=null)
    //        Yadid.Save(bw);
    }
    public static Person Load(BinaryReader br)
    {
        Person person = new Person();
        person.Name = br.ReadString();
        person.Age = br.ReadInt32();
        person.Height = br.ReadDouble();
       // person.Yadid = Person.Load(br);
        return person;
    }

}

Thats the teachers code. it works.
i just applied different variables and added a class. Why doesnt my code work? it follows the same principles, or does it not?


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка времени выполнения system indexoutofrangeexception индекс находился вне границ массива стек
  • Ошибка времени выполнения system formatexception входная строка имела неверный формат