Моя цель - сериализовать список новых структур и многократно сохранять его в одном и том же файле (например, если список содержит 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
и создать новый список со структурами в файле?
Я был бы признателен, если бы мог получить некоторый код для этого.