简体   繁体   中英

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.ReadTimeout' threw an exception of type '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 . 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). That length exceeds the remaining length you have available to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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