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(f开发者_Python百科ileName))
using (view.IncidentWriter = new BinaryWriter(file))
{
foreach (short dataItem in view.Data)
{
view.IncidentWriter.Write(dataItem);
}
}
The binary reader is binary writer's friend, you can make it yours
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
.
精彩评论