嘗試從二進制文件讀取簡單記錄結構,但會收到以下錯誤消息。問題是什麼?從二進制文件讀取錯誤
類型的未處理的異常「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);
{
...
}
,但我得到了同樣的錯誤。
我相信這個問題很明顯......你正試圖讀取文件的末尾。你有一個有你所描述問題的示例文件嗎? – SuperOli
嘗試顛倒你的做法,同時,讓它變得有一段時間。在做...的同時,「安全測試」可能來得太晚 - 如果你有漂移,你應該有「不要」,你已經「做了」。 –
@ B.Clay Shannon剛剛嘗試過,我得到了同樣的錯誤信息。 – user3396486