繁体   English   中英

我正在尝试从C#中的自定义文件类型读取

[英]I'm trying to read from a custom file type in C#

我正在尝试从创建的自定义文件类型读取和写入,如下所示:

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

主要方法:

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

但我不断收到异常:

流结束异常

ss.name = br.ReadString();

我使用十六进制编辑器打开了文件,然后看到数据正确写入,并且文件流同时出现以下异常

“ ms.WriteTimeout”引发了“ System.InvalidOperationException”类型的异常

'ms.ReadTimeout'引发了'System.InvalidOperationException'类型的异常

我的数据结构是:

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

您使用“ SEARCH”的六个字符初始化了magic ,但是使用5调用了ReadChars 这将导致下一个读取的字符串不正确。 ReadString尝试获取要读取的长度,该长度将使用char H初始化(部分长度...字符串为Unicode)。 该长度超出了您可以使用的剩余长度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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