C#中将list进行序列化并使用SharpZipLib进行压缩
生活随笔
收集整理的這篇文章主要介紹了
C#中将list进行序列化并使用SharpZipLib进行压缩
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
場景
ICSharpCode.SharpZipLib.dll 下載:
https://download.csdn.net/download/badao_liumang_qizhi/11586902
實現
新建Winform窗體程序。
打開資源管理器-引用-右鍵-添加--瀏覽
選擇剛才上面下載的ICSharpCode.SharpZipLib.dll,點擊確定。
?
右擊項目-添加-類
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace ProtoBufTest {[Serializable]class Person{public Person(int id ,string password) {this.Id = id;this.Password = password;}private int id;public int Id{get { return id; }set { id = value; }}private string password;public string Password{get { return password; }set { password = value; }}} }在窗體上拖拽一個Button按鈕,然后雙擊進其點擊事件。
?private void button7_Click(object sender, EventArgs e){DateTime begin = DateTime.Now;Console.WriteLine("二進制壓縮開始" + begin.ToString("yyyy-MM-dd HH:mm:ss"));//初始化數據for (int i = 0; i < 10000; i++){personList.Add(new Person(i,"密碼"+i));}try{//創建內存流對象MemoryStream ms = new MemoryStream();?????????????????//序列化對象BinaryFormatter formatter = new BinaryFormatter();formatter.Serialize(ms, this.personList);//把內存流對象寫入字節數組??????????????????byte[] buffer = ms.ToArray();//關閉內存流對象ms.Close();//釋放資源?????????????????????????????????ms.Dispose();????????????????????????????????????????????????????????????FileStream fs = File.Create(@"E:\testdata1\Record3.zip");//創建文件//創建zip輸出流ZipOutputStream zipOutputStream = new ZipOutputStream(fs, buffer.Length);//ZipEntry用于表示Zip文件條目 --將會在壓縮文件中創建Record3.data文件ZipEntry entry = new ZipEntry("Record3.data");//將其放進壓縮文件中zipOutputStream.PutNextEntry(entry);//將字節數組寫入文件zipOutputStream.Write(buffer, 0, buffer.Length);zipOutputStream.Finish();zipOutputStream.Close();zipOutputStream.Dispose();//關閉流fs.Close();//釋放對象fs.Dispose();??????????????????????????????????????????????????????????}catch (Exception ex){Console.WriteLine(ex.Message);}DateTime end = DateTime.Now;TimeSpan ts = end - begin;Console.WriteLine("二進制壓縮結束" + end.ToString("yyyy-MM-dd HH:mm:ss"));Console.WriteLine("共花費 " + ts.TotalSeconds);}具體使用見注釋。
運行效果
?
將其解壓
?
?
總結
以上是生活随笔為你收集整理的C#中将list进行序列化并使用SharpZipLib进行压缩的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#中使用Directory实现对文件夹
- 下一篇: C#中将list使用ProtoBuf进行