繁体   English   中英

如何解决“无法阅读超出流末尾的错误”错误?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM