C# 如何使用BinaryWriter进行写和读?

C# 如何使用BinaryWriter进行写和读?,c#,C#,我有一段代码,它在编写二进制文件时起作用: using (BinaryWriter binWriter = new BinaryWriter(File.Open(f.fileName, FileMode.Create))) { for (int i = 0; i < f.histogramValueList.

我有一段代码,它在编写二进制文件时起作用:

using (BinaryWriter binWriter =
                                new BinaryWriter(File.Open(f.fileName, FileMode.Create)))
                            {
                                for (int i = 0; i < f.histogramValueList.Count; i++)
                                {

                                    binWriter.Write(f.histogramValueList[(int)i]);



                                }
                                binWriter.Close();
                            }
但第一件事是我如何写下所有这些,并使它在文件中,它自己是由一个字符串或其他东西来识别,所以当我读回文件时,我将能够把每个列表放在一个新的

第二件事是我现在如何读回文件,以便将每个列表添加到新列表中? 现在很简单,我写一个列表,阅读并将其添加到列表中。 但是现在我添加了更多的三个列表,那么我该怎么做呢


谢谢。

要获得答案,请考虑如何获取列表中您刚刚序列化的项目数

作弊代码:在项目之前写下集合中的项目数。阅读时,一定要倒转

writer.Write(items.Count());
// write items.Count() items.
阅读:

int count = reader.ReadInt32();
items = new List<ItemType>();
// read count item objects and add to items collection.
int count=reader.ReadInt32();
项目=新列表();
//读取计数项目对象并添加到项目集合。

只有当您需要与第三方系统、设备或驱动程序交互时,这样的书写和阅读才真正适用。如果您只想持久化一组列表,为什么不使用二进制序列化呢?您可以为它提供一个具有适用列表的对象,甚至一个列表列表。有关更多信息,请查看BinaryFormatter。
writer.Write(items.Count());
// write items.Count() items.
int count = reader.ReadInt32();
items = new List<ItemType>();
// read count item objects and add to items collection.