C#中将list进行二进制序列化并保存数据到文件
生活随笔
收集整理的這篇文章主要介紹了
C#中将list进行二进制序列化并保存数据到文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
場景
將一個對象list進行二進制序列化并將數據寫進文件。
實現
新建Winforn程序,然后拖拽兩個Button。
第一個Button用來構建一個1000長度的list對象。
先聲明一個全局的list變量。
List<Person> personList = new List<Person>();然后在點擊事件中:
?private void button3_Click(object sender, EventArgs e){DateTime begin = DateTime.Now;Console.WriteLine("普通初始化數據開始" + begin.ToString("yyyy-MM-dd HH:mm:ss"));for (int i = 1; i <= 1000;i++ ){personList.Add(new Person(i,"密碼"+i));}DateTime end = DateTime.Now;TimeSpan ts = end - begin;Console.WriteLine("普通初始化數據結束" + end.ToString("yyyy-MM-dd HH:mm:ss"));Console.WriteLine("共花費" + ts.TotalSeconds);}構建好數據后,在第二個按鈕的點擊事件中
? private void button5_Click(object sender, EventArgs e){DateTime begin = DateTime.Now;Console.WriteLine("普通保存數據開始" + begin.ToString("yyyy-MM-dd HH:mm:ss"));?????using (System.IO.FileStream fs = new System.IO.FileStream(@"E:\testdata1\Record1.data", System.IO.FileMode.Create, System.IO.FileAccess.Write)){BinaryFormatter formatter = new BinaryFormatter();formatter.Serialize(fs, personList);}DateTime end = DateTime.Now;TimeSpan ts = end - begin;Console.WriteLine("普通保存數據結束" + end.ToString("yyyy-MM-dd HH:mm:ss"));Console.WriteLine("共花費 " + ts.TotalSeconds);}將其進行二進制序列化并保存到文件。
總結
以上是生活随笔為你收集整理的C#中将list进行二进制序列化并保存数据到文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#中使用ProtoBuf提高序列化速度
- 下一篇: C#中使用ProtoBuf将list进行