[英]How to fix the “unable to read beyond the end of stream”-error?
我收到以下錯誤:
“無法閱讀超出流的結尾”
我這樣寫文件:
FileStream path = new FileStream(@"C:\Users\Moosa Raza\Desktop\byte.txt", FileMode.CreateNew);
BinaryWriter file = new BinaryWriter(path);
int a = int.Parse(Console.ReadLine());
double b = double.Parse(Console.ReadLine());
string c = Console.ReadLine();
file.Write(b);
file.Write(c);
file.Write(a);
輸入是a = 12,b = 13和c = raza
然后像這樣閱讀:
FileStream path = new FileStream(@"C:\Users\Computer\Desktop\byte.txt", FileMode.Open);
BinaryReader s = new BinaryReader(path);
int a = s.ReadInt32();
double b = s.ReadDouble();
string c = s.ReadString();
Console.WriteLine("int = {0} , double = {1} , string = {2}",a,b,c);
Console.ReadKey();
您必須以完全相同的順序讀取文件。 根據您的評論 ,您編寫的順序是:雙精度,字符串,整數。
但是,讀取代碼按int,double,string的順序讀取。
這會導致讀取器讀取錯誤的字節,並將某個值解釋為不正確的字符串長度,從而嘗試讀取文件末尾之外的內容。
確保閱讀順序與書寫順序相同。
請嘗試這個。 通過使用“使用”范圍,當您完成寫入或讀取文件時,它將關閉文件。 代碼也將更加簡潔。
using (var sw = new StreamWriter(@"C:\Users\Computer\Desktop\byte.txt"))
{
sw.WriteLine(int.Parse(Console.ReadLine()));
sw.WriteLine(double.Parse(Console.ReadLine()));
sw.WriteLine(Console.ReadLine());
}
using (var sr = new StreamReader(@"C:\Users\Computer\Desktop\byte.txt"))
{
int a = int.Parse(sr.ReadLine());
double b = double.Parse(sr.ReadLine());
string c = sr.ReadLine();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.