我有一个简单的过程来将图书馆书籍列表(TBook 类型)写入二进制文件,如下所示:
static void SaveToFile(List<TBook> lib)
{
FileStream currentFile;
BinaryWriter writerToFile;
currentFile = new FileStream("MyLibrary.bin", FileMode.Create);
writerToFile = new BinaryWriter(currentFile);
foreach (TBook book in lib)
{
writerToFile.Write(book.Title);
writerToFile.Write(book.Author);
writerToFile.Write(book.Genre);
writerToFile.Write(book.BookID);
}
writerToFile.Close();
currentFile.Close();
}
但是,当尝试读取二进制文件并将内容加载到列表中时,出现错误:
mscorlib.dll 中出现“System.IO.EndOfStreamException”类型的未处理异常
附加信息:无法读取超出流末尾的内容。
这是我尝试将二进制文件再次读回结构的子例程:
static List<TBook> LoadDataFromFile (List<TBook>library)
{
FileStream currentFile;
BinaryReader readerFromFile;
currentFile = new FileStream("MyLibrary.bin", FileMode.Open);
readerFromFile= new BinaryReader(currentFile);
while (currentFile.Position < currentFile.Length)
{
TBook CurrentRecord = new TBook();
CurrentRecord.Title = readerFromFile.ReadString();
CurrentRecord.Author = readerFromFile.ReadString();
CurrentRecord.Genre = readerFromFile.ReadString();
CurrentRecord.BookID = readerFromFile.ReadInt16();
library.Add(CurrentRecord);
}
readerFromFile.Close();
currentFile.Close();
return library;
}
我认为问题出在以下行:
while (currentFile.Position < currentFile.Length)
注意:结构设置如下:
struct TBook
{
public string Title;
public string Author;
public string Genre;
public int BookID;
}
泛舟湖上清波郎朗
相关分类