C#中将list进行序列化并使用SharpZipLib进行压缩
生活随笔
收集整理的這篇文章主要介紹了
C#中将list进行序列化并使用SharpZipLib进行压缩
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
場景
ICSharpCode.SharpZipLib.dll 下載:
https://download.csdn.net/download/badao_liumang_qizhi/11586902
實現(xiàn)
新建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按鈕,然后雙擊進(jìn)其點擊事件。
?private void button7_Click(object sender, EventArgs e){DateTime begin = DateTime.Now;Console.WriteLine("二進(jìn)制壓縮開始" + begin.ToString("yyyy-MM-dd HH:mm:ss"));//初始化數(shù)據(jù)for (int i = 0; i < 10000; i++){personList.Add(new Person(i,"密碼"+i));}try{//創(chuàng)建內(nèi)存流對象MemoryStream ms = new MemoryStream();?????????????????//序列化對象BinaryFormatter formatter = new BinaryFormatter();formatter.Serialize(ms, this.personList);//把內(nèi)存流對象寫入字節(jié)數(shù)組??????????????????byte[] buffer = ms.ToArray();//關(guān)閉內(nèi)存流對象ms.Close();//釋放資源?????????????????????????????????ms.Dispose();????????????????????????????????????????????????????????????FileStream fs = File.Create(@"E:\testdata1\Record3.zip");//創(chuàng)建文件//創(chuàng)建zip輸出流ZipOutputStream zipOutputStream = new ZipOutputStream(fs, buffer.Length);//ZipEntry用于表示Zip文件條目 --將會在壓縮文件中創(chuàng)建Record3.data文件ZipEntry entry = new ZipEntry("Record3.data");//將其放進(jìn)壓縮文件中zipOutputStream.PutNextEntry(entry);//將字節(jié)數(shù)組寫入文件zipOutputStream.Write(buffer, 0, buffer.Length);zipOutputStream.Finish();zipOutputStream.Close();zipOutputStream.Dispose();//關(guān)閉流fs.Close();//釋放對象fs.Dispose();??????????????????????????????????????????????????????????}catch (Exception ex){Console.WriteLine(ex.Message);}DateTime end = DateTime.Now;TimeSpan ts = end - begin;Console.WriteLine("二進(jìn)制壓縮結(jié)束" + end.ToString("yyyy-MM-dd HH:mm:ss"));Console.WriteLine("共花費(fèi) " + ts.TotalSeconds);}具體使用見注釋。
運(yùn)行效果
?
將其解壓
?
?
總結(jié)
以上是生活随笔為你收集整理的C#中将list进行序列化并使用SharpZipLib进行压缩的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#中使用Directory实现对文件夹
- 下一篇: C#中将list使用ProtoBuf进行