c# - 如何修复“无法读取超出流末尾”的错误?
问题描述
我收到以下错误:
“无法读取超出流末尾的内容”</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();
解决方案
您必须按照与写入文件完全相同的顺序读取文件。根据你的评论,你写的顺序是:double、string、int。
然而,读取代码按 int、double、string 的顺序读取。
这会导致阅读器读取错误的字节,并将某个值解释为不正确的字符串长度,从而试图读取超出文件末尾的内容。
确保按照与写作相同的顺序阅读。
推荐阅读
- c++ - 如何在 C++ 中获得两个 int 的公共数字?示例:(1234, 41567) --> 1 4
- python - Pandas 数据框中的浮点数
- c - skiplist 的 C 实现中的概率论问题
- visual-studio-code - VSCode 终端未打开(退出代码:3221225794)
- android - RecyclerView 中如何使用自定义第一个元素使第一个元素的高度等于屏幕的大小
- r - Shiny - 如何保存以超越 renderTable 中的每个更改?
- mongodb - 在 MERN 中插入数据时验证失败
- python - Python Datacompy:如何获得完整的比较报告
- wordpress - Wordpress htaccess - 我想将所有 404 页面重定向到主页,但 wp-admin 和另一个 URL 除外
- postgresql - 在防火墙后面的 Windows 机器上手动安装 ora2pg [DBD::Oracle] 不能直接访问互联网