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

I did some quick method to write a file from a stream but it’s not done yet. I receive this exception and I can’t find why:

Unable to read beyond the end of the stream

Is there anyone who could help me debug it?

public static bool WriteFileFromStream(Stream stream, string toFile)
{
    FileStream fileToSave = new FileStream(toFile, FileMode.Create);
    BinaryWriter binaryWriter = new BinaryWriter(fileToSave);

    using (BinaryReader binaryReader = new BinaryReader(stream))
    {
        int pos = 0;
        int length = (int)stream.Length;

        while (pos < length)
        {
            int readInteger = binaryReader.ReadInt32();

            binaryWriter.Write(readInteger);

            pos += sizeof(int);
        }
    }

    return true;
}

Thanks a lot!

rick schott's user avatar

rick schott

21k5 gold badges52 silver badges81 bronze badges

asked Oct 19, 2011 at 1:59

Tommy B.'s user avatar

Not really an answer to your question but this method could be so much simpler like this:

public static void WriteFileFromStream(Stream stream, string toFile) 
{
    // dont forget the using for releasing the file handle after the copy
    using (FileStream fileToSave = new FileStream(toFile, FileMode.Create))
    {
        stream.CopyTo(fileToSave);
    }
} 

Note that i also removed the return value since its pretty much useless since in your code, there is only 1 return statement

Apart from that, you perform a Length check on the stream but many streams dont support checking Length.

As for your problem, you first check if the stream is at its end. If not, you read 4 bytes. Here is the problem. Lets say you have a input stream of 6 bytes. First you check if the stream is at its end. The answer is no since there are 6 bytes left. You read 4 bytes and check again. Ofcourse the answer is still no since there are 2 bytes left. Now you read another 4 bytes but that ofcourse fails since there are only 2 bytes. (readInt32 reads the next 4 bytes).

answered Oct 19, 2011 at 2:35

Polity's user avatar

PolityPolity

14.7k2 gold badges40 silver badges39 bronze badges

1

I presume that the input stream have ints only (Int32). You need to test the PeekChar() method,

while (binaryReader.PeekChar() != -1)
{
  int readInteger = binaryReader.ReadInt32();
  binaryWriter.Write(readInteger);          
}

answered Oct 19, 2011 at 2:13

KV Prajapati's user avatar

KV PrajapatiKV Prajapati

93.5k19 gold badges147 silver badges186 bronze badges

1

You are doing while (pos < length) and length is the actual length of the stream in bytes. So you are effectively counting the bytes in the stream and then trying to read that many number of ints (which is incorrect). You could take length to be stream.Length / 4 since an Int32 is 4 bytes.

answered Oct 19, 2011 at 2:04

Jesus Ramos's user avatar

Jesus RamosJesus Ramos

22.9k10 gold badges56 silver badges88 bronze badges

try

int length = (int)binaryReader.BaseStream.Length;

answered Oct 19, 2011 at 2:08

Joe Mancuso's user avatar

Joe MancusoJoe Mancuso

2,0791 gold badge16 silver badges17 bronze badges

After reading the stream by the binary reader the position of the stream is at the end, you have to set the position to zero «stream.position=0;»

answered Apr 19, 2013 at 21:14

Amina's user avatar

AminaAmina

357 bronze badges

SashaPl

50 / 37 / 9

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

Сообщений: 406

1

08.06.2015, 21:27. Показов 3262. Ответов 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



Модератор

Эксперт по электронике

8324 / 4223 / 1602

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

Сообщений: 13,154

Записей в блоге: 4

08.06.2015, 21:31

2

Правду пишет.
Файл открыт на запись (rewrite), не закрыт, на чтение не открыт. Какой read?



1



50 / 37 / 9

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

Сообщений: 406

08.06.2015, 21:33

 [ТС]

3

Цитата
Сообщение от ФедосеевПавел
Посмотреть сообщение

Правду пишет.
Файл открыт на запись (rewrite), не закрыт, на чтение не открыт. Какой read?

(censored) я дурак. Все время это забываю писать. Большое спасибо.



0



Модератор

Эксперт по электронике

8324 / 4223 / 1602

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

Сообщений: 13,154

Записей в блоге: 4

08.06.2015, 21:36

4

Подредактируй сообщение — «это не по-кодексу».



0



50 / 37 / 9

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

Сообщений: 406

08.06.2015, 21:47

 [ТС]

5

Цитата
Сообщение от ФедосеевПавел
Посмотреть сообщение

Подредактируй сообщение — «это не по-кодексу».

Как подредактировать?



0



Модератор

Эксперт по электронике

8324 / 4223 / 1602

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

Сообщений: 13,154

Записей в блоге: 4

08.06.2015, 21:54

6

По истечении 5 минут — уже никак. Но до того — кнопка «Правка» в правом нижнем углу сообщения.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

08.06.2015, 21:54

Помогаю со студенческими работами здесь

Ошибка «project1.lpr(35,0) Fatal: Syntax error, «BEGIN» expected but «end of file» found»
type
tarray= array of integer;
var
a:tarray;
m,s,k:integer;
procedure…

Ошибка «Fatal: Syntax error, «BEGIN» expected but «END» found»
Ввожу
unit Unit1;

{$mode objfpc}{$H+}

interface

uses
Classes, SysUtils, FileUtil,…

Ошибка «Syntax error, «BEGIN» expected but «end of file» found»
В чём заключается ошибка в 73 строке под названием &quot;Syntax error, &quot;BEGIN&quot; expected but &quot;end of…

«Ошибка заголовка gif-файла» при загрузке его из Stream-а
почему вот при таком коде —
pac:=TPaker.Create(‘pack.pck’);
stream:=TMemoryStream.Create;…

прокоментировать функцию «ввод из типизированного файла»
Всем здрасте. Помогите плих нужно прокоментировать в тех местах где поставил пустые &quot;//&quot; и там где…

Удалить из типизированного файла первую из букв «о»
Имеется файл, элементами которого являются отдельные символы. Удалить из него первую из букв &quot;о&quot;…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

6

Irbos

0 / 0 / 0

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

Сообщений: 189

1

.NET Core

13.03.2021, 13:04. Показов 5688. Ответов 3

Метки нет (Все метки)


На строчке ret = br.ReadSingle(); выдаёт эту ошибку.
«System.IO.EndOfStreamException: «Unable to read beyond the end of the stream.»»

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
            float ret = 0.0f;
 
            string finalPath = g_Path_Main + @"" + FilePath;
 
            if (!File.Exists(finalPath))
                return ret;
 
            using (var fs = new FileStream(finalPath, FileMode.Open))
            {
                using (var br = new BinaryReader(fs))
                {
                    br.BaseStream.Position += 18;
 
                    ret = br.ReadSingle();
                }
            }
 
            return ret;

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

0

Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

13.03.2021, 13:04

Ответы с готовыми решениями:

Ошибка времени выполнения unable to read beyond the end of stream
uses graphabc;
var a, b, c:integer;
i:file of integer;
begin
SetWindowWidth(500);…

Пробная база данных.EndOfException: Unable to read the end of the stream (после попытки чтения первой строки)
Написал на С# учебно-тренировочную базу данных,но работать
она не хочет.Прошу помочь…

Вывод типизированного файла «unable to read beyond the end of the stream»
uses crt;
label 1,2;
var f1:file of integer;
x,i,i1,i2,n:integer;
begin
assign(f1,…

stream.read(v,stream.size); //здесь ошибка при исполнении
var
stream:Tfilestream;
v:variant;
begin

3

Администратор

Эксперт .NET

15226 / 12265 / 4902

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

Сообщений: 24,867

Записей в блоге: 1

13.03.2021, 13:41

2

Irbos, какая длина у файла?

0

0 / 0 / 0

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

Сообщений: 189

13.03.2021, 13:52

 [ТС]

3

OwenGlendower, там несколько файлов и у них разная длина, но она больше чем 18 байт примерно 1000-100к

0

OwenGlendower

Администратор

Эксперт .NET

15226 / 12265 / 4902

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

Сообщений: 24,867

Записей в блоге: 1

13.03.2021, 14:08

4

Лучший ответ Сообщение было отмечено Irbos как решение

Решение

Цитата
Сообщение от Irbos
Посмотреть сообщение

она больше чем 18 байт

Очевидно нет раз выдается исключение о невозможности чтения.

Добавлено через 2 минуты
Попробуйте добавить проверку

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
using (var fs = new FileStream(finalPath, FileMode.Open))
{
    const int start = 18;
    if (fs.Length >= start+sizeof(float))
    {
        using (var br = new BinaryReader(fs))
        {
            br.BaseStream.Position = start;
 
            ret = br.ReadSingle();
        }
    }
}

1

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

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

Ошибка на 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

thats a permission issue. you didnt follow the install instructions correctly.

**How to Install:**

**+** Stop your Torrent from seeding (close it, maybe check your task manager)

**+** Move the Warhammer Online — Return of Reckoning outside the ReturnofReckoning-March2020 folder and move it to c: … for instance move it to c:Games
(but **NOT** inside c: Program Files or c: Program Files (x86); it should be in a folder which it have write access)

**+** Remove the write-protection from all the files in the Warhammer Online — Return of Reckoning folder.
(right click on the War Online — RoR folder > properties > disable the read-only box)

**+** Check that your whole Warhammer Online — Return of Reckoning folder is whitelisted in your Antivirus program and check if your Firewall or Maleware doesn’t interfere with the install.

**+** You may also try running the launcher with Administrator privileges.
(Right click on the RoRLauncher.exe > properties > run administrator)

**+** Run the RoRLauncher.exe
**+** Let it update (sometimes it needs a few seconds until it starts)
**+** Exit launcher and rerun it again
**+** Repeat the last 2-steps until there is no update left
**+** Launch the game

**!!!** [If you don’t have DirectX 9.0c, installed it is required, and now this is also included in the torrent. In the ReturnOfReckoning-March2020 folder find the dx90c folder, open that and run DXSETUP.exe]

Describe the bug

When I double click the left mouse button a hoodwink.vmdl_c file an «Unable to read beyond the end of the stream» error appears. If you click on the ‘Continue’ button, it opens a tab hoodwink.vmdl_c with emty subtab MODEL.

************** Exception Text **************
System.IO.EndOfStreamException: Unable to read beyond the end of the stream.
   at System.IO.BinaryReader.InternalRead(Int32 numBytes)
   at System.IO.BinaryReader.ReadInt16()
   at ValveResourceFormat.ResourceTypes.ModelAnimation.Animation.ReadSegment(Int64 frame, IKeyValueCollection segment, IKeyValueCollection decodeKey, AnimDecoderType[] decoderArray, Frame& outFrame) in D:aValveResourceFormatValveResourceFormatValveResourceFormatResourceResourceTypesModelAnimationAnimation.cs:line 225
   at ValveResourceFormat.ResourceTypes.ModelAnimation.Animation.ConstructFromDesc(IKeyValueCollection animDesc, IKeyValueCollection decodeKey, AnimDecoderType[] decoderArray, IKeyValueCollection[] segmentArray) in D:aValveResourceFormatValveResourceFormatValveResourceFormatResourceResourceTypesModelAnimationAnimation.cs:line 190
   at ValveResourceFormat.ResourceTypes.ModelAnimation.Animation..ctor(IKeyValueCollection animDesc, IKeyValueCollection decodeKey, AnimDecoderType[] decoderArray, IKeyValueCollection[] segmentArray) in D:aValveResourceFormatValveResourceFormatValveResourceFormatResourceResourceTypesModelAnimationAnimation.cs:line 28
   at ValveResourceFormat.ResourceTypes.ModelAnimation.Animation.<>c__DisplayClass17_0.<FromData>b__0(IKeyValueCollection anim) in D:aValveResourceFormatValveResourceFormatValveResourceFormatResourceResourceTypesModelAnimationAnimation.cs:line 44
   at System.Linq.Enumerable.SelectArrayIterator`2.MoveNext()
   at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
   at ValveResourceFormat.ResourceTypes.Model.GetEmbeddedAnimations() in D:aValveResourceFormatValveResourceFormatValveResourceFormatResourceResourceTypesModel.cs:line 109
   at GUI.Types.Renderer.ModelSceneNode.LoadAnimations() in D:aValveResourceFormatValveResourceFormatGUITypesRendererModelSceneNode.cs:line 214
   at GUI.Types.Renderer.ModelSceneNode..ctor(Scene scene, Model model, String skin, Boolean loadAnimations) in D:aValveResourceFormatValveResourceFormatGUITypesRendererModelSceneNode.cs:line 67
   at GUI.Types.Renderer.GLModelViewer.LoadScene() in D:aValveResourceFormatValveResourceFormatGUITypesRendererGLModelViewer.cs:line 74
   at GUI.Types.Renderer.GLSceneViewer.OnLoad(Object sender, EventArgs e) in D:aValveResourceFormatValveResourceFormatGUITypesRendererGLSceneViewer.cs:line 85
   at GUI.Controls.GLViewerControl.OnLoad(Object sender, EventArgs e) in D:aValveResourceFormatValveResourceFormatGUIControlsGLViewerControl.cs:line 246
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
   at System.Windows.Forms.TabControl.UpdateTabSelection(Boolean updateFocus)
   at System.Windows.Forms.TabControl.OnHandleCreated(EventArgs e)
   at System.Windows.Forms.Control.WmCreate(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.TabControl.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, WM msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
System.Private.CoreLib
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Private.CoreLib.dll
----------------------------------------
VRF
    Assembly Version: 0.1.9.0
    Win32 Version: 0.1.9.731
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/VRF.dll
----------------------------------------
System.Windows.Forms
    Assembly Version: 5.0.7.0
    Win32 Version: 5.0.721.26307
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Windows.Forms.dll
----------------------------------------
System.ComponentModel.Primitives
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.ComponentModel.Primitives.dll
----------------------------------------
System.Windows.Forms.Primitives
    Assembly Version: 5.0.7.0
    Win32 Version: 5.0.721.26307
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Windows.Forms.Primitives.dll
----------------------------------------
System.Runtime.InteropServices
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Runtime.InteropServices.dll
----------------------------------------
System.Drawing.Primitives
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Drawing.Primitives.dll
----------------------------------------
System.Collections.Specialized
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Collections.Specialized.dll
----------------------------------------
System.Diagnostics.TraceSource
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Diagnostics.TraceSource.dll
----------------------------------------
System.Console
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Console.dll
----------------------------------------
System.IO.FileSystem
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.IO.FileSystem.dll
----------------------------------------
System.Drawing.Common
    Assembly Version: 5.0.0.2
    Win32 Version: 5.0.421.11614
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Drawing.Common.dll
----------------------------------------
Microsoft.Win32.Primitives
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/Microsoft.Win32.Primitives.dll
----------------------------------------
System.ComponentModel.EventBasedAsync
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.ComponentModel.EventBasedAsync.dll
----------------------------------------
Accessibility
    Assembly Version: 4.0.0.0
    Win32 Version: 5.0.721.26307
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/Accessibility.dll
----------------------------------------
System.Linq
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Linq.dll
----------------------------------------
System.ComponentModel.TypeConverter
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.ComponentModel.TypeConverter.dll
----------------------------------------
System.ComponentModel
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.ComponentModel.dll
----------------------------------------
System.Collections.Concurrent
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Collections.Concurrent.dll
----------------------------------------
Microsoft.Win32.SystemEvents
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.20.51904
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/Microsoft.Win32.SystemEvents.dll
----------------------------------------
System.Collections.NonGeneric
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Collections.NonGeneric.dll
----------------------------------------
System.Resources.Extensions
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.20.51904
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Resources.Extensions.dll
----------------------------------------
System.ObjectModel
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.ObjectModel.dll
----------------------------------------
System.Diagnostics.FileVersionInfo
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Diagnostics.FileVersionInfo.dll
----------------------------------------
System.Diagnostics.Process
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Diagnostics.Process.dll
----------------------------------------
ValveKeyValue
    Assembly Version: 0.5.0.0
    Win32 Version: 0.5.0.4
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/ValveKeyValue.dll
----------------------------------------
System.Runtime.InteropServices.RuntimeInformation
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Runtime.InteropServices.RuntimeInformation.dll
----------------------------------------
System.Collections
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Collections.dll
----------------------------------------
System.Runtime.Serialization.Formatters
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Runtime.Serialization.Formatters.dll
----------------------------------------
System.Runtime.CompilerServices.Unsafe
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Runtime.CompilerServices.Unsafe.dll
----------------------------------------
System.Threading
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Threading.dll
----------------------------------------
System.Text.RegularExpressions
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Text.RegularExpressions.dll
----------------------------------------
ValvePak
    Assembly Version: 1.0.2.35
    Win32 Version: 1.0.2.35
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/ValvePak.dll
----------------------------------------
ValveResourceFormat
    Assembly Version: 0.1.9.0
    Win32 Version: 0.1.9.731
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/ValveResourceFormat.dll
----------------------------------------
SkiaSharp
    Assembly Version: 2.80.0.0
    Win32 Version: 2.80.2.0
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/SkiaSharp.dll
----------------------------------------
SkiaSharp.Views.Desktop.Common
    Assembly Version: 2.80.0.0
    Win32 Version: 2.80.2.0
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/SkiaSharp.Views.Desktop.Common.dll
----------------------------------------
System.Windows.Forms.Design
    Assembly Version: 5.0.7.0
    Win32 Version: 5.0.721.26307
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Windows.Forms.Design.dll
----------------------------------------
ZstdSharp
    Assembly Version: 0.3.0.0
    Win32 Version: 0.3.0.0
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/ZstdSharp.dll
----------------------------------------
K4os.Compression.LZ4
    Assembly Version: 1.2.6.0
    Win32 Version: 1.2.6
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/K4os.Compression.LZ4.dll
----------------------------------------
OpenTK
    Assembly Version: 3.3.1.0
    Win32 Version: 3.3.1
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/OpenTK.dll
----------------------------------------
OpenTK.GLControl
    Assembly Version: 3.1.0.0
    Win32 Version: 3.1.0
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/OpenTK.GLControl.dll
----------------------------------------
System.Linq.Expressions
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Linq.Expressions.dll
----------------------------------------
Anonymously Hosted DynamicMethods Assembly
    Assembly Version: 0.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Private.CoreLib.dll
----------------------------------------
System.Private.Uri
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Private.Uri.dll
----------------------------------------
System.Diagnostics.StackTrace
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Diagnostics.StackTrace.dll
----------------------------------------
System.Reflection.Metadata
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Reflection.Metadata.dll
----------------------------------------
System.Collections.Immutable
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Collections.Immutable.dll
----------------------------------------
System.IO.MemoryMappedFiles
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.IO.MemoryMappedFiles.dll
----------------------------------------
System.IO.Compression
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.IO.Compression.dll
----------------------------------------
Microsoft.Win32.Registry
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/Microsoft.Win32.Registry.dll
----------------------------------------
System.Drawing
    Assembly Version: 5.0.7.0
    Win32 Version: 5.0.721.26307
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Drawing.dll
----------------------------------------
SharpGLTF.Core
    Assembly Version: 1.0.0.0
    Win32 Version: 1.0.0.0
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/SharpGLTF.Core.dll
----------------------------------------
SharpGLTF.Toolkit
    Assembly Version: 1.0.0.0
    Win32 Version: 1.0.0.0
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/SharpGLTF.Toolkit.dll
----------------------------------------
System.Text.Json
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Text.Json.dll
----------------------------------------
System.Memory
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Memory.dll
----------------------------------------
System.Text.Encodings.Web
    Assembly Version: 5.0.0.1
    Win32 Version: 5.0.721.25508
    CodeBase: file:///C:/Users/Username/AppData/Local/Temp/.net/VRF/pptqb30n.dwq/System.Text.Encodings.Web.dll
----------------------------------------

************** JIT Debugging **************

What Valve game does this happen in

Dota 2

Reference file in a Source 2 game

D:SteamSteamAppscommondota 2 betagamedotapak01_dir.vpkmodelsheroeshoodwinkhoodwink.vmdl_c

Expected behavior

I expect when I double click the left mouse button a hoodwink.vmdl_c file, no error should appear and the MODEL subtab should display the loaded model that I can export.

What version of VRF are you using? On what platform?

Version of VRF: 0.1.9.731 Platform: Windows 8.1 x64

Irbos

0 / 0 / 0

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

Сообщений: 199

1

.NET Core

13.03.2021, 13:04. Показов 6628. Ответов 3

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

На строчке ret = br.ReadSingle(); выдаёт эту ошибку.
«System.IO.EndOfStreamException: «Unable to read beyond the end of the stream.»»

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
            float ret = 0.0f;
 
            string finalPath = g_Path_Main + @"" + FilePath;
 
            if (!File.Exists(finalPath))
                return ret;
 
            using (var fs = new FileStream(finalPath, FileMode.Open))
            {
                using (var br = new BinaryReader(fs))
                {
                    br.BaseStream.Position += 18;
 
                    ret = br.ReadSingle();
                }
            }
 
            return ret;

0

Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

13.03.2021, 13:04

Ответы с готовыми решениями:

Ошибка времени выполнения unable to read beyond the end of stream
uses graphabc;
var a, b, c:integer;
i:file of integer;
begin
SetWindowWidth(500);…

Пробная база данных.EndOfException: Unable to read the end of the stream (после попытки чтения первой строки)
Написал на С# учебно-тренировочную базу данных,но работать
она не хочет.Прошу помочь…

Вывод типизированного файла «unable to read beyond the end of the stream»
uses crt;
label 1,2;
var f1:file of integer;
x,i,i1,i2,n:integer;
begin
assign(f1,…

stream.read(v,stream.size); //здесь ошибка при исполнении
var
stream:Tfilestream;
v:variant;
begin

3

Администратор

Эксперт .NET

15668 / 12629 / 5003

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

Сообщений: 25,708

Записей в блоге: 1

13.03.2021, 13:41

2

Irbos, какая длина у файла?

0

0 / 0 / 0

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

Сообщений: 199

13.03.2021, 13:52

 [ТС]

3

OwenGlendower, там несколько файлов и у них разная длина, но она больше чем 18 байт примерно 1000-100к

0

OwenGlendower

Администратор

Эксперт .NET

15668 / 12629 / 5003

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

Сообщений: 25,708

Записей в блоге: 1

13.03.2021, 14:08

4

Лучший ответ Сообщение было отмечено Irbos как решение

Решение

Цитата
Сообщение от Irbos
Посмотреть сообщение

она больше чем 18 байт

Очевидно нет раз выдается исключение о невозможности чтения.

Добавлено через 2 минуты
Попробуйте добавить проверку

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
using (var fs = new FileStream(finalPath, FileMode.Open))
{
    const int start = 18;
    if (fs.Length >= start+sizeof(float))
    {
        using (var br = new BinaryReader(fs))
        {
            br.BaseStream.Position = start;
 
            ret = br.ReadSingle();
        }
    }
}

1

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

  • 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

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.

  • 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

  • Ошибка времени выполнения system indexoutofrangeexception индекс находился вне границ массива стек
  • Ошибка времени выполнения system formatexception входная строка имела неверный формат
  • Ошибка времени выполнения object reference not set to an instance of an object
  • Ошибка времени выполнения input string was not in a correct format
  • Ошибка времени выполнения database error occurred