首页 > 解决方案 > 如何修复“无法读取超出流末尾”的错误?

问题描述

我收到以下错误:

“无法读取超出流末尾的内容”</p>

我这样写文件:

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();

标签: c#

解决方案


您必须按照与写入文件完全相同的顺序读取文件。根据你的评论,你写的顺序是:double、string、int。

然而,读取代码按 int、double、string 的顺序读取。

这会导致阅读器读取错误的字节,并将某个值解释为不正确的字符串长度,从而试图读取超出文件末尾的内容。

确保按照与写作相同的顺序阅读。


推荐阅读