[英]I'm trying to read from a custom file type in C#
I'm trying to read and write from a custom file type that I created, like this: 我正在尝试从创建的自定义文件类型读取和写入,如下所示:
public static byte[] writeTo(Structures.SearchDS s)
{
var o = new MemoryStream();
var b = new BinaryWriter(o);
b.Write(s.magic);
b.Write(s.name);
b.Write(s.age);
b.Write(s.b.ElementAt(0).Houseno);
b.Write(s.b.ElementAt(0).location);
return o.ToArray();
}
public static Structures.SearchDS readSearchFile(byte[] a)
{
MemoryStream ms = new MemoryStream(a);
BinaryReader br = new BinaryReader(ms);
Structures.SearchDS ss = new Structures.SearchDS();
ss.magic=br.ReadChars(5);
ss.name = br.ReadString();
ss.age = br.ReadUInt16();
ss.b[0] = new Structures.House();
ss.b[0].Houseno = br.ReadString();
ss.b[0].location = br.ReadString();
return ss;
}
Main method: 主要方法:
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
byte[] testFile=Tools.writeTo(Tools.adding());
File.WriteAllBytes("test3.search", testFile);
Structures.SearchDS ss1 = Tools.Write(File.ReadAllBytes("test.search"));
Console.WriteLine(ss1.age);
Console.WriteLine(ss1.name);
Console.WriteLine(ss1.magic);
ss1.b[0] = new Structures.House();
Console.WriteLine(ss1.b.ElementAt(0).Houseno);
Console.WriteLine(ss1.b.ElementAt(0).location);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
but I keep getting the exception: 但我不断收到异常:
End of stream exception
流结束异常
at 在
ss.name = br.ReadString();
I opened the file with a hex editor and I see my data written properly and file stream gives the following exceptions at the same time 我使用十六进制编辑器打开了文件,然后看到数据正确写入,并且文件流同时出现以下异常
'ms.WriteTimeout' threw an exception of type 'System.InvalidOperationException'
“ ms.WriteTimeout”引发了“ System.InvalidOperationException”类型的异常
'ms.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
'ms.ReadTimeout'引发了'System.InvalidOperationException'类型的异常
My data structures are: 我的数据结构是:
public class SearchDS
{
public char[] magic = { 'S', 'E', 'A', 'R', 'C', 'H' };
public string name;
public UInt16 age;
public House[] b = new House[1];
}
public class House { public string Houseno; public string location; }
You initialized magic
with the six characters of "SEARCH", but you call ReadChars
with 5 . 您使用“ SEARCH”的六个字符初始化了
magic
,但是使用5调用了ReadChars
。 This causes the very next read string to be incorrect; 这将导致下一个读取的字符串不正确。 the
ReadString
tries to get the length to read, which is going to be initialized with the char H (well part of it... strings are Unicode). ReadString
尝试获取要读取的长度,该长度将使用char H初始化(部分长度...字符串为Unicode)。 That length exceeds the remaining length you have available to you. 该长度超出了您可以使用的剩余长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.