简体   繁体   中英

binary back to List<Int16>

I have written a list of values to a binary file using the binary writer.

I was wondering if someone could show me how I could extract the list of int16 values back from this binary file?

Thanks in advance

using (var file = File.Create(fileName))
using (view.IncidentWriter = new BinaryWriter(file))
{
    foreach (short dataItem in view.Data)
    {
        view.IncidentWriter.Write(dataItem);
    }
}

二进制读取器是二进制写入器的朋友,您可以将其设为您的

The easiest way to do this is to prefix the data with the expected count:

        var list = new List<short>{1,2,3,4,5};
        using (var file = File.Create("my.data"))
        using (var writer = new BinaryWriter(file))
        {
            writer.Write(list.Count);
            foreach(var item in list) writer.Write(item);
        }

        using (var file = File.OpenRead("my.data"))
        using (var reader = new BinaryReader(file))
        {
            int count = reader.ReadInt32();
            list = new List<short>(count);
            for (int i = 0; i < count; i++)
                list.Add(reader.ReadInt16());
        }

Otherwise, you have to detect EOF, which is easy enough with a Stream , but a pain with a BinaryReader .

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