在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
System.IO.Compression命名空單中有兩個奪縮流類DeflateStream和GZipStream。 以GZipStream為例,用代碼來學習。
using System.IO.Compression;
using System.IO; namespace MyZip { public partial class Form1 : Form { public Form1() { InitializeComponent(); btnCompressed.Click += new EventHandler(btnCompressed_Click); btnUnCompressed.Click += new EventHandler(btnUnCompressed_Click); } /// <summary> /// 壓縮文件 /// </summary> /// <param name="asSouceFile">被壓縮的文件的完整路徑</param> /// <param name="asZipFileName">被解壓文件的完整路徑</param> private void SaveCompressdFile(string asSouceFile, string asZipFileName) { string sData = ReadFile(asSouceFile); FileStream fsStream = new FileStream(asZipFileName, FileMode.Create, FileAccess.Write); //壓縮 GZipStream gzStream = new GZipStream(fsStream, CompressionMode.Compress); StreamWriter swWriter = new StreamWriter(gzStream); swWriter.Write(sData); swWriter.Close(); } /// <summary> /// 解壓文件 /// </summary> /// <param name="asZipFileName">被解壓文件的完整路徑</param> /// <param name="asUnZipFileName">解壓後文件的完整路徑</param> private void LoadCompressdFile(string asZipFileName,string asUnZipFileName) { FileStream fsStream = new FileStream(asZipFileName, FileMode.Open, FileAccess.Read); //解壓縮 GZipStream gzStream = new GZipStream(fsStream, CompressionMode.Decompress); StreamReader srReader = new StreamReader(gzStream); string sData= srReader.ReadToEnd(); srReader.Close(); WriteFile(asUnZipFileName, sData); } /// <summary> /// 讀取文件 /// </summary> /// <param name="asSouceFile">被讀取文件的完整路徑</param> /// <returns></returns> private string ReadFile(string asSouceFileName) { string sValue=""; try { FileStream fsStream = new FileStream(asSouceFileName, FileMode.Open, FileAccess.Read); StreamReader srReader = new StreamReader(asSouceFileName); sValue = srReader.ReadToEnd(); srReader.Close(); } catch (Exception ex) { throw ex; } return sValue; } /// <summary> /// 寫入文件 /// </summary> /// <param name="asFileName">寫入後文件的完整路徑</param> /// <param name="asData">被寫入的資料</param> /// <returns></returns> private void WriteFile(string asFileName,string asData) { FileStream fsStream = new FileStream(asFileName, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter swWriter = new StreamWriter(fsStream); swWriter.Write(asData); swWriter.Close(); } /// <summary> /// 壓縮按鈕事件的方法 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void btnCompressed_Click(object sender, EventArgs e) { SaveCompressdFile(@"D:\log.txt", @"D:\zip.txt"); } /// <summary> /// 解壓縮壓按鈕事件的方法 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void btnUnCompressed_Click(object sender, EventArgs e) { LoadCompressdFile(@"D:\zip.txt", @"D:\unzip.txt"); } } } |
请发表评论