从二进制文件读取错误

编程入门 行业动态 更新时间:2024-10-09 11:20:24
本文介绍了从二进制文件读取错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

试图从二进制文件中读取简单的记录结构,但得到以下错误消息.有什么问题吗?

Trying to read simple record structure from Binary file, but get the following error message. What is the problem?

类型为'System.IO.EndOfStreamException'的未处理异常 发生在mscorlib.dll

An unhandled exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll

其他信息:无法读到流的末尾.

Additional information: Unable to read beyond the end of the stream.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Reading_from_Binary_File { class Program { struct TBook { public string author; public string title; public string genre; //TGenreTypes genre; public int bookid; }; static void Main(string[] args) { FileStream currentFile; BinaryReader readerFromFile; currentFile = new FileStream("Test.bin", FileMode.Open); readerFromFile = new BinaryReader(currentFile); TBook myBooks; do { //Now read from file and write to console window myBooks.title = readerFromFile.ReadString(); myBooks.author = readerFromFile.ReadString(); myBooks.genre = readerFromFile.ReadString(); // myBooks.genre = (TGenreTypes)Enum.Parse(typeof(TGenreTypes),readerFromFile.ReadString()); myBooks.bookid = readerFromFile.ReadInt16(); Console.WriteLine("Title: {0}", myBooks.title); Console.WriteLine("Author: {0}", myBooks.author); Console.WriteLine("Genre: {0}", myBooks.genre); Console.WriteLine("BookID: {0}", myBooks.bookid); } while (currentFile.Position < currentFile.Length); //close the streams currentFile.Close(); readerFromFile.Close(); Console.ReadLine(); } } }

更新: 我也尝试过

while (currentFile.Position < currentFile.Length); { ... }

但是我遇到了同样的错误.

but I get the same error.

推荐答案

尝试交换

myBooks.bookid = readerFromFile.ReadInt16();

使用

myBooks.bookid = readerFromFile.ReadInt32();

默认情况下,int是System.Int32的别名.

as by default the int is an alias for System.Int32.

在您的结构中

struct TBook { public string author; public string title; public string genre; //TGenreTypes genre; public int bookid; };

您已指定int bookid,然后将其为System.Int32. 因此,仅读取2 bytes而不是4 bytes将导致流中剩下2 bytes.因此循环不会中断.然后,在循环中,您将尝试读取不存在的另一组数据"(仅2个字节).

you have specified int bookid which would then be a System.Int32. So reading just 2 bytes instead of 4 bytes will result in having 2 bytes left in the stream. So the loop won't break. In the loop you will then try to read another "set" of data which isn't there (just the 2 bytes).

更多推荐

从二进制文件读取错误

本文发布于:2023-11-24 16:52:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626050.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   二进制文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!