简体   繁体   English

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

[英]How to fix the “unable to read beyond the end of stream”-error?

I receive following error: 我收到以下错误:

“unable to read beyond the end of stream” “无法阅读超出流的结尾”

I write the file like this: 我这样写文件:

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

input is a = 12, b = 13 and c = raza 输入是a = 12,b = 13和c = raza

Then read it like this: 然后像这样阅读:

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

You must read the file in the exact same order you write it. 您必须以完全相同的顺序读取文件。 According to your comment , the order in which you write is: double, string, int. 根据您的评论 ,您编写的顺序是:双精度,字符串,整数。

The reading code however, reads in the order int, double, string. 但是,读取代码按int,double,string的顺序读取。

This causes the reader to read the wrong bytes, and interpret a certain value as an incorrect string length, thereby trying to read beyond the end of the file. 这会导致读取器读取错误的字节,并将某个值解释为不正确的字符串长度,从而尝试读取文件末尾之外的内容。

Make sure you read in the same order as you write. 确保阅读顺序与书写顺序相同。

please try this. 请尝试这个。 By using 'using' scope, it will close the file when you finish writing or reading it. 通过使用“使用”范围,当您完成写入或读取文件时,它将关闭文件。 Also the code will be a bit cleaner. 代码也将更加简洁。

        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