【发布时间】:2016-01-05 16:10:37
【问题描述】:
试图从二进制文件中读取简单的记录结构,但得到以下错误消息。有什么问题?
“System.IO.EndOfStreamException”类型的未处理异常 发生在 mscorlib.dll 中
附加信息:无法读取超出流末尾的内容。
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。使用do...while,“安全测试”可能来得太晚了——如果你明白我的意思,当你应该“不”的时候,你已经“做了”。
-
@ B.Clay Shannon 刚刚尝试过,我得到了同样的错误信息。
-
I@SuperOil 如果有帮助,我可以向您展示我用来创建二进制文件的 BinaryWriter 程序吗?
-
@user3396486:我已经发布了一个答案,我想它会解决你的问题。
标签: c# binaryfiles