读取二进制文件错误

Reading from a binary file error

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

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);
{
    ...
}

但我得到了同样的错误。

将你的 do...while 反转为 while (do) 就像这样:

while (currentFile.Position < currentFile.Length)            
{
    //Now read from file and write to console window
    . . .
}

通过这种方式,在实际尝试访问该位置之前,测试是否到达 "danger zone"。如果您等到尝试之后再检查,最后一次尝试(正如您发现的那样)将失败。

您可能想要 this 捷克语。

尝试交换

myBooks.bookid = readerFromFile.ReadInt16();

myBooks.bookid = readerFromFile.ReadInt32();

默认情况下 intSystem.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 留在流中。所以循环不会中断。在循环中,您将尝试读取另一个 "set" 不存在的数据(仅 2 个字节)。