C#實(shí)現(xiàn)批量壓縮和解壓縮的示例代碼
更新時(shí)間:2022年12月26日 09:42:46 作者:芝麻粒兒
這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)批量壓縮和解壓縮的功能,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下
實(shí)踐過程
效果

代碼
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
#region 壓縮文件及文件夾
/// <summary>
/// 遞歸壓縮文件夾方法
/// </summary>
/// <param name="FolderToZip"></param>
/// <param name="ZOPStream">壓縮文件輸出流對(duì)象</param>
/// <param name="ParentFolderName"></param>
private bool ZipFileDictory(string FolderToZip, ZipOutputStream ZOPStream, string ParentFolderName)
{
bool res = true;
string[] folders, filenames;
ZipEntry entry = null;
FileStream fs = null;
Crc32 crc = new Crc32();
try
{
//創(chuàng)建當(dāng)前文件夾
entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/")); //加上 “/” 才會(huì)當(dāng)成是文件夾創(chuàng)建
ZOPStream.PutNextEntry(entry);
ZOPStream.Flush();
//先壓縮文件,再遞歸壓縮文件夾
filenames = Directory.GetFiles(FolderToZip);
foreach (string file in filenames)
{
//打開壓縮文件
fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file)));
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
ZOPStream.PutNextEntry(entry);
ZOPStream.Write(buffer, 0, buffer.Length);
}
}
catch
{
res = false;
}
finally
{
if (fs != null)
{
fs.Close();
fs = null;
}
if (entry != null)
{
entry = null;
}
GC.Collect();
GC.Collect(1);
}
folders = Directory.GetDirectories(FolderToZip);
foreach (string folder in folders)
{
if (!ZipFileDictory(folder, ZOPStream, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip))))
{
return false;
}
}
return res;
}
/// <summary>
/// 壓縮目錄
/// </summary>
/// <param name="FolderToZip">待壓縮的文件夾</param>
/// <param name="ZipedFile">壓縮后的文件名</param>
/// <returns></returns>
private bool ZipFileDictory(string FolderToZip, string ZipedFile)
{
bool res;
if (!Directory.Exists(FolderToZip))
{
return false;
}
ZipOutputStream ZOPStream = new ZipOutputStream(File.Create(ZipedFile));
ZOPStream.SetLevel(6);
res = ZipFileDictory(FolderToZip, ZOPStream, "");
ZOPStream.Finish();
ZOPStream.Close();
return res;
}
/// <summary>
/// 壓縮文件和文件夾
/// </summary>
/// <param name="FileToZip">待壓縮的文件或文件夾</param>
/// <param name="ZipedFile">壓縮后生成的壓縮文件名,全路徑格式</param>
/// <returns></returns>
public bool Zip(String FileToZip, String ZipedFile)
{
if (Directory.Exists(FileToZip))
{
return ZipFileDictory(FileToZip, ZipedFile);
}
else
{
return false;
}
}
#endregion
#region 復(fù)制文件//
public void CopyFile(string[] list,string strNewPath,ToolStripProgressBar TSPBar)
{
try
{
TSPBar.Maximum = list.Length;
string strNewFile = "c:\\" + strNewPath;
if (!Directory.Exists(strNewFile))
Directory.CreateDirectory(strNewFile);
foreach (object objFile in list)
{
string strFile = objFile.ToString();
string Filename = strFile.Substring(strFile.LastIndexOf("\\") + 1, strFile.Length - strFile.LastIndexOf("\\") - 1);
File.Copy(strFile, strNewFile+"\\"+Filename, true);
TSPBar.Value += 1;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
#region 解壓文件
/// <summary>
/// 解壓文件
/// </summary>
/// <param name="FileToUpZip">待解壓的文件</param>
/// <param name="ZipedFolder">指定解壓目標(biāo)目錄</param>
public void UnZip(string FileToUpZip, string ZipedFolder)
{
if (!File.Exists(FileToUpZip))
{
return;
}
if (!Directory.Exists(ZipedFolder))
{
Directory.CreateDirectory(ZipedFolder);
}
ZipInputStream ZIPStream = null;
ZipEntry theEntry = null;
string fileName;
FileStream streamWriter = null;
try
{
//生成一個(gè)GZipInputStream流,用來打開壓縮文件
ZIPStream = new ZipInputStream(File.OpenRead(FileToUpZip));
while ((theEntry = ZIPStream.GetNextEntry()) != null)
{
if (theEntry.Name != String.Empty)
{
fileName = Path.Combine(ZipedFolder, theEntry.Name);
//判斷文件路徑是否是文件夾
if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
{
Directory.CreateDirectory(fileName);
continue;
}
//生成一個(gè)文件流,它用來生成解壓文件
streamWriter = File.Create(fileName);
int size = 2048;//指定壓縮塊的大小,一般為2048的倍數(shù)
byte[] data = new byte[2048];//指定緩沖區(qū)的大小
while (true)
{
size = ZIPStream.Read(data, 0, data.Length);//讀入一個(gè)壓縮塊
if (size > 0)
{
streamWriter.Write(data, 0, size);//寫入解壓文件代表的文件流
}
else
{
break;//若讀到壓縮文件尾,則結(jié)束
}
}
}
}
}
finally
{
if (streamWriter != null)
{
streamWriter.Close();
streamWriter = null;
}
if (theEntry != null)
{
theEntry = null;
}
if (ZIPStream != null)
{
ZIPStream.Close();
ZIPStream = null;
}
GC.Collect();
GC.Collect(1);
}
}
#endregion
string[] files;//存儲(chǔ)要進(jìn)行壓縮的文件數(shù)組
string[] files2;//存儲(chǔ)要進(jìn)行解壓縮的文件數(shù)組
private void button1_Click(object sender, EventArgs e)//選擇批量壓縮的文件
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
files = openFileDialog1.FileNames;
string file = "";
for (int i = 0; i < files.Length; i++)
{
file += files[i].ToString() + ",";
}
file = file.Remove(file.LastIndexOf(","));
txtfiles.Text = file;
}
}
private void button3_Click(object sender, EventArgs e)//選擇批量解壓縮的文件
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
files2 = openFileDialog2.FileNames;
string file = "";
for (int i = 0; i < files2.Length; i++)
{
file += files2[i].ToString() + ",";
}
file = file.Remove(file.LastIndexOf(","));
txtfiles2.Text = file;
}
}
private void button2_Click(object sender, EventArgs e)//批量壓縮
{
try
{
if (txtfiles.Text.Trim()!="")
{
toolStripProgressBar1.Maximum = files.Length;
if (files.Length > 1)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string strNewPath = DateTime.Now.ToString("yyyyMMddhhmmss");
CopyFile(files, strNewPath, toolStripProgressBar1);
Zip("c:\\"+strNewPath,saveFileDialog1.FileName);
Directory.Delete("c:\\" + strNewPath, true);
MessageBox.Show("壓縮文件成功");
}
}
toolStripProgressBar1.Value = 0;
}
else
{
MessageBox.Show("警告:請(qǐng)選擇要進(jìn)行批量壓縮的文件!","警告",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
catch { }
}
private void button4_Click(object sender, EventArgs e)
{
try
{
if (txtfiles2.Text.Trim() != "")
{
toolStripProgressBar1.Maximum = files2.Length;
for (int i = 0; i < files2.Length; i++)
{
toolStripProgressBar1.Value = i;
string path = files2[i].ToString();
string newpath = path.Remove(path.LastIndexOf("\\") + 1);
UnZip(path, newpath);
}
toolStripProgressBar1.Value = 0;
MessageBox.Show("解壓縮成功!");
}
else
{
MessageBox.Show("警告:請(qǐng)選擇要進(jìn)行批量解壓縮的文件!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch { }
}
}
partial class Form1
{
/// <summary>
/// 必需的設(shè)計(jì)器變量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的資源。
/// </summary>
/// <param name="disposing">如果應(yīng)釋放托管資源,為 true;否則為 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗體設(shè)計(jì)器生成的代碼
/// <summary>
/// 設(shè)計(jì)器支持所需的方法 - 不要
/// 使用代碼編輯器修改此方法的內(nèi)容。
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.button1 = new System.Windows.Forms.Button();
this.txtfiles = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.button2 = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.button3 = new System.Windows.Forms.Button();
this.txtfiles2 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.button4 = new System.Windows.Forms.Button();
this.openFileDialog2 = new System.Windows.Forms.OpenFileDialog();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripProgressBar1 = new System.Windows.Forms.ToolStripProgressBar();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.statusStrip1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.button1);
this.groupBox1.Controls.Add(this.txtfiles);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.ForeColor = System.Drawing.Color.Black;
this.groupBox1.Location = new System.Drawing.Point(12, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(432, 63);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "批量壓縮文件";
//
// button1
//
this.button1.Location = new System.Drawing.Point(383, 24);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(43, 23);
this.button1.TabIndex = 2;
this.button1.Text = "...";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// txtfiles
//
this.txtfiles.BackColor = System.Drawing.Color.White;
this.txtfiles.Location = new System.Drawing.Point(116, 25);
this.txtfiles.Name = "txtfiles";
this.txtfiles.ReadOnly = true;
this.txtfiles.Size = new System.Drawing.Size(260, 21);
this.txtfiles.TabIndex = 1;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 28);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(113, 12);
this.label1.TabIndex = 0;
this.label1.Text = "選擇要壓縮的文件:";
//
// openFileDialog1
//
this.openFileDialog1.InitialDirectory = "c:";
this.openFileDialog1.Multiselect = true;
//
// button2
//
this.button2.Location = new System.Drawing.Point(128, 172);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(85, 23);
this.button2.TabIndex = 3;
this.button2.Text = "批量壓縮";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.button3);
this.groupBox2.Controls.Add(this.txtfiles2);
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.ForeColor = System.Drawing.Color.Black;
this.groupBox2.Location = new System.Drawing.Point(12, 91);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(432, 63);
this.groupBox2.TabIndex = 4;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "批量解壓縮文件";
//
// button3
//
this.button3.Location = new System.Drawing.Point(383, 24);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(43, 23);
this.button3.TabIndex = 2;
this.button3.Text = "...";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// txtfiles2
//
this.txtfiles2.BackColor = System.Drawing.Color.White;
this.txtfiles2.Location = new System.Drawing.Point(128, 24);
this.txtfiles2.Name = "txtfiles2";
this.txtfiles2.ReadOnly = true;
this.txtfiles2.Size = new System.Drawing.Size(248, 21);
this.txtfiles2.TabIndex = 1;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 28);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(125, 12);
this.label2.TabIndex = 0;
this.label2.Text = "選擇要解壓縮的文件:";
//
// button4
//
this.button4.Location = new System.Drawing.Point(233, 172);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(85, 23);
this.button4.TabIndex = 5;
this.button4.Text = "批量解壓縮";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// openFileDialog2
//
this.openFileDialog2.DefaultExt = "RAR";
this.openFileDialog2.Filter = "壓縮文件|*.rar;*.zip";
this.openFileDialog2.InitialDirectory = "c:";
this.openFileDialog2.Multiselect = true;
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1,
this.toolStripProgressBar1});
this.statusStrip1.Location = new System.Drawing.Point(0, 200);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(456, 22);
this.statusStrip1.TabIndex = 6;
this.statusStrip1.Text = "statusStrip1";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.AutoSize = false;
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(100, 17);
this.toolStripStatusLabel1.Text = "執(zhí)行進(jìn)度:";
this.toolStripStatusLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// toolStripProgressBar1
//
this.toolStripProgressBar1.Name = "toolStripProgressBar1";
this.toolStripProgressBar1.Size = new System.Drawing.Size(200, 16);
//
// saveFileDialog1
//
this.saveFileDialog1.Filter = "RAR|*.rar";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(456, 222);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.button4);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.button2);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "批量解壓縮";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox txtfiles;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.TextBox txtfiles2;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.OpenFileDialog openFileDialog2;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
}
以上就是C#實(shí)現(xiàn)批量壓縮和解壓縮的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于C#壓縮 解壓縮的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#中public變量不能被unity面板識(shí)別的解決方案
這篇文章主要介紹了C#中public變量不能被unity面板識(shí)別的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04
使用C#實(shí)現(xiàn)RTP數(shù)據(jù)包傳輸 參照RFC3550
本篇文章小編為大家介紹,使用C#實(shí)現(xiàn)RTP數(shù)據(jù)包傳輸 參照RFC3550,需要的朋友參考下2013-04-04
C#實(shí)現(xiàn)完善Excel不規(guī)則合并單元格數(shù)據(jù)導(dǎo)入的示例代碼
本文主要介紹了C#實(shí)現(xiàn)完善Excel不規(guī)則合并單元格數(shù)據(jù)導(dǎo)入的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-02-02

