在做網絡傳輸檔案的小例子的時候,當傳輸的檔案比較大的時候,我們通常都是将檔案經過壓縮之後才進行傳輸,以前都是利用第三方插件來對檔案進行壓縮的,但是現在我發現了c#自帶的類庫也能夠實作檔案的壓縮,實際上是對資料的壓縮吧,為什麼說是對具體的資料經行壓縮了,請看下面實作壓縮的代碼吧。
注意在用c#自帶的類庫實作檔案壓縮和解壓的時候需要添加下面的引用:
using System.IO.Compression;
using System.IO;
壓縮檔案的代碼如下:
/// <summary>
///壓縮檔案
/// </summary>
/// <param name="filePath">需要被壓縮檔案的路徑</param>
private void FileCompression(string filePath)
{
StreamReader sr = new StreamReader(filePath);
//讀取出檔案中的内容來。
string data=sr.ReadToEnd();
//壓縮檔案的字尾名可以随意起。
FileStream filedata = new FileStream("myCompression.mZP", FileMode.Create, FileAccess.Write);
GZipStream zip = new GZipStream(filedata, CompressionMode.Compress);
StreamWriter sw = new StreamWriter(zip);
//将檔案的内容寫入到壓縮的流當中
sw.Write(data);
zip.Close();
sr.Close();
filedata.Close();
//關閉流一定要按照流的順序來,否則會出現異常:無法通路已關閉的檔案。
// zip.Close();
}
然後實作解壓的代碼與上面類似
解壓檔案的代碼如下:
private void fileDeCompression()
{
//将以壓縮的檔案變為一個檔案流
FileStream fileCompression = File.OpenRead("myCompression.mZP");
GZipStream gzp = new GZipStream(fileCompression, CompressionMode.Decompress);
StreamReader sr = new StreamReader(gzp);
//讀取出解壓後的資料
string data = sr.ReadToEnd();
MessageBox.Show(data);
gzp.Close();
fileCompression.Close();
sr.Close();
}
通過使用上面的兩個方法即可實作對檔案或者是資料的壓縮和解壓。
使用自帶的類也會存在一些缺點:無法對檔案夾經行壓縮。
轉載于:https://www.cnblogs.com/mingjiatang/p/3780957.html