我的目标是序列化新结构的列表,并重复地将其保存到同一文件中(例如,只要列表有5个结构,就将新结构附加到同一文件中)。
class Program
{
static void Main(string[] args)
{
List<struct_realTime2> list_temp2 = new List<struct_realTime2>(100000);
// ADD 5 new structs to list_temp2
for (int num = 0; num < 5; num++)
{
list_temp2.Add(new struct_realTime2 { indexNum = num,
currentTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ffffff"),
currentType = "type" });
}
// WRITE structs
using (var fileStream = new FileStream("file.bin", FileMode.Append))
{
var bFormatter = new BinaryFormatter();
foreach (struct_realTime2 stru in list_temp2)
{
bFormatter.Serialize(fileStream, stru);
}
list_temp2.Clear() // empty the list
}
// READ structs
var list = new List<struct_realTime2>();
using (var fileStream = new FileStream("file.bin", FileMode.Open))
{
var bFormatter = new BinaryFormatter();
while (fileStream.Position != fileStream.Length)
{
list.Add((struct_realTime2)bFormatter.Deserialize(fileStream));
}
}
// PRINT OUT structs in the file
foreach (struct_realTime2 stru in list)
{
string content_struct = stru.indexNum.ToString() + ", " + stru.currentTime;
Console.WriteLine(content_struct);
}
// WRITE list
using (var fileStream = new FileStream("file_list.bin", FileMode.Append))
{
var bFormatter = new BinaryFormatter();
bFormatter.Serialize(fileStream, list_temp2);
}
}
}
[Serializable]
public struct struct_realTime2
{
public int indexNum { get; set; }
public string currentTime { get; set; }
public string currentType { get; set; }
}< the result >
C:\Users\null\source\repos\ConsoleApp6\ConsoleApp6\bin\Debug>ConsoleApp6.exe
0, 2019-11-10 15:31:52.044207
1, 2019-11-10 15:31:52.047225
2, 2019-11-10 15:31:52.047225
3, 2019-11-10 15:31:52.047225
4, 2019-11-10 15:31:52.047225
C:\Users\null\source\repos\ConsoleApp6\ConsoleApp6\bin\Debug>ConsoleApp6.exe
0, 2019-11-10 15:31:52.044207
1, 2019-11-10 15:31:52.047225
2, 2019-11-10 15:31:52.047225
3, 2019-11-10 15:31:52.047225
4, 2019-11-10 15:31:52.047225
0, 2019-11-10 15:31:55.700680
1, 2019-11-10 15:31:55.703627
2, 2019-11-10 15:31:55.703627
3, 2019-11-10 15:31:55.703627
4, 2019-11-10 15:31:55.703627如果我将每个结构附加到文件并读取它们,它就可以很好地工作。但我希望避免使用循环将每个结构附加到文件,而只希望重复地将the list itself附加到文件并读取该文件。
添加列表似乎很有效,因为每当我运行该程序时,file_list.bin的大小都会加倍。但是,如何读取file_list.bin并使用文件中的结构创建新的列表呢?
如果我能得到一些代码,我将不胜感激。
发布于 2019-11-10 17:02:17
CSV
如果您想将数据附加到现有文件中,我建议使用csv样式的序列化。
BinaryFormatter
如果序列化一个列表(数组会更好),那么
bFormatter.Serialize(fileStream, list_temp2.ToArray());是
var list = (struct_realTime2[])bFormatter.Deserialize(fileStream));如果将新数据附加到现有文件(而不是每次都覆盖文件),则此操作可能不起作用。
https://stackoverflow.com/questions/58786312
复制相似问题