我有一个简单的过程来将图书馆书籍列表(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; }
1 回答
泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
当您将数据序列化为二进制时,您的反序列化代码必须完全遵循序列化代码;否则你的反序列化器开始从相邻位置读取垃圾,最终导致异常或用错误的数据默默地填充你的结构。
这对调用不匹配:
writerToFile.Write(book.BookID);
....
CurrentRecord.BookID = readerFromFile.ReadInt16();
很难看出这个问题,因为BinaryWriter重载了Write方法。由于book.BookIDis 的类型int是 的别名Int32,因此对 的调用Write被解析为Write(Int32)。因此,相应的 read 也必须是 read Int32,而不是Int16:
CurrentRecord.BookID = readerFromFile.ReadInt32();
- 1 回答
- 0 关注
- 87 浏览
添加回答
举报
0/150
提交
取消