Csharp 利用ICSharpCode.SharpZipLib解壓文件

简介: /* *http://www.koders.com/csharp/fid7241B3C8598C20BA18652B5BB5C19D220988E2D4.aspx?s=file * http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx * http://www.eggheadcafe.com/tutori
/*
 *http://www.koders.com/csharp/fid7241B3C8598C20BA18652B5BB5C19D220988E2D4.aspx?s=file
 * http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
 * http://www.eggheadcafe.com/tutorials/aspnet/9ce6c242-c14c-4969-9251-af95e4cf320f/zip--unzip-folders-and-f.aspx
 * http://www.eggheadcafe.com/community/csharp/2/10060149/zip-a-file-using-icsharpcodesharpziplibzip.aspx
 * http://www.eggheadcafe.com/tutorials/csharp/9ce6c242-c14c-4969-9251-af95e4cf320f/zip--unzip-folders-and-files-with-c.aspx
 * 
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Management;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;
using System.IO;
using System.Collections;
using System.Windows;


namespace CompressFolders
{
    /// <summary>
    /// 20120530 
    /// 涂聚文 Geovin Du
    /// </summary>
    public partial class Form1 : Form
    {
        string strBaseDir = "";
        /// <summary>
        /// 
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            //指定文件
            //this.saveFileDialog1.Filter = "压缩文件(zip)|*.zip";
            //this.saveFileDialog1.Title = "保存文件";
            //this.saveFileDialog1.FileName = "数据备份";
            //this.saveFileDialog1.InitialDirectory =Application.StartupPath;
            //this.saveFileDialog1.RestoreDirectory = true;
            //string Fname = "";
            //if (this.saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    string[] filenames ={ "Properties", "Form1.resx", "frmMain.Designer.cs", "Program.cs", "Form1.Designer.cs", "Form1.resx", "frmMain.cs" };//可以自己定义所压缩的文件
            //    Fname = this.saveFileDialog1.FileName;
            //    ZipOutputStream s = new ZipOutputStream(File.Create(Fname));//创建压缩文件的目录及名称
            //    s.Password = "geovindu";//设置压缩文件的密码
            //    s.SetLevel(6);// 0 - store only to 9 - means best compression
            //    foreach (string file in filenames)
            //    {
            //        if (Directory.Exists(Application.StartupPath + @"/" + file))
            //        {
            //            strBaseDir = Application.StartupPath + @"/" + file + @"/";//压缩文件夹
            //            addZipEntry(strBaseDir, s);
            //        }
            //        else
            //        {
            //            FileStream fs = File.OpenRead(Application.StartupPath + @"/" + file);//打开文件读取
            //            byte[] buffer = new byte[fs.Length];
            //            fs.Read(buffer, 0, buffer.Length);
            //            string strEntryName = file;
            //            ZipEntry entry = new ZipEntry(strEntryName);
            //            s.PutNextEntry(entry);
            //            s.Write(buffer, 0, buffer.Length);
            //            fs.Close();
            //        }
            //    }
            //    s.Finish();
            //    s.Close();
            //}


        }
        /// <summary>
        /// 壓縮文件夾
        /// </summary>
        /// <param name="PathStr"></param>
        /// <param name="s"></param>
        private void addZipEntry(string PathStr, ZipOutputStream s)
        {
            DirectoryInfo di = new DirectoryInfo(PathStr);
            foreach (DirectoryInfo item in di.GetDirectories())
            {
                addZipEntry(item.FullName, s);
            }
            foreach (FileInfo item in di.GetFiles())
            {
                if (item.FullName.Replace(strBaseDir, "") != "Thumbs.db")
                {
                    FileStream fs = File.OpenRead(item.FullName);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    string strEntryName = item.FullName.Replace(strBaseDir, "");
                    strEntryName = @"Properties/" + strEntryName;
                    ZipEntry entry = new ZipEntry(strEntryName);
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                    fs.Close();
                }
            }
        }
        /// <summary>
        /// 解压缩
        /// </summary>
        /// <param name="zipfile"></param>
        /// <param name="directory"></param>
        private void Unzip(string zipfile, string directory)
        {
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            ZipInputStream zis = new ZipInputStream(File.OpenRead(zipfile));
            string str = zis.Password;
            zis.Password = "塗聚文";
            ZipEntry theEntry = null;
            while ((theEntry = zis.GetNextEntry()) != null)
            {
                ZipConstants.DefaultCodePage = 936;
                string directoryName = Path.GetDirectoryName(theEntry.Name);//directoryName=null
                string fileName = Path.GetFileName(theEntry.Name);
                
                if (directoryName != string.Empty)
                {
                    if ((directoryName == "Properties") && (!Directory.Exists(directory + @"/" + directoryName)))
                    {
                        Directory.CreateDirectory(directory + @"/" + directoryName);
                    }
                }
                if (fileName != string.Empty)
                {
                    FileStream streamWriter = File.Create(Path.Combine(directory, theEntry.Name));
                    int size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = zis.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    streamWriter.Close();
                }
            }
            zis.Close();
        }


        /// <summary>
        ///壓縮 100M大文件進程不行
        /// 塗聚文 Geovin Du
        /// </summary>
        /// <param name="inputFolderPath"></param>
        /// <param name="outputPathAndFile"></param>
        /// <param name="password"></param>
        public static void ZipFiles(string inputFolderPath, string outputPathAndFile, string password)
        {
            ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
            int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
            // find number of chars to remove     // from orginal file path
            TrimLength += 1; //remove '\'
            FileStream ostream;
            byte[] obuffer;
            string outPath = inputFolderPath + @"\" + outputPathAndFile;
            ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream
            if (password != null && password != String.Empty)
                oZipStream.Password = password;
            oZipStream.SetLevel(9); // maximum compression
            ZipEntry oZipEntry;
            foreach (string Fil in ar) // for each file, generate a zipentry
            {
                oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
                oZipStream.PutNextEntry(oZipEntry);

                if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory
                {
                    ostream = File.OpenRead(Fil);
                    obuffer = new byte[ostream.Length];
                    ostream.Read(obuffer, 0, obuffer.Length);
                    oZipStream.Write(obuffer, 0, obuffer.Length);
                }
            }
            oZipStream.Finish();
            oZipStream.Close();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Dir"></param>
        /// <returns></returns>
        public static ArrayList GenerateFileList(string Dir)
        {
            ArrayList fils = new ArrayList();
            bool Empty = true;
            foreach (string file in Directory.GetFiles(Dir)) // add each file in directory
            {
                fils.Add(file);
                Empty = false;
            }

            if (Empty)
            {
                if (Directory.GetDirectories(Dir).Length == 0)
                // if directory is completely empty, add it
                {
                    fils.Add(Dir + @"/");
                }
            }

            foreach (string dirs in Directory.GetDirectories(Dir)) // recursive
            {
                foreach (object obj in GenerateFileList(dirs))
                {
                    fils.Add(obj);
                }
            }
            return fils; // return file list
        }

        /// <summary>
        /// 打開選擇文件夾
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                //MessageBox.Show(fbd.SelectedPath);
                this.textBox1.Text = fbd.SelectedPath;
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSave_Click(object sender, EventArgs e)
        {
            ZipFiles(this.textBox1.Text.Trim(), this.textBox2.Text.Trim(), "geovindu");

        }
        /// <summary>
        /// 選擇文件夾
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                //MessageBox.Show(fbd.SelectedPath);
                this.textBox2.Text = fbd.SelectedPath;
            }
        }

    }
}

目录
相关文章
|
C#
ICSharpCode.TextEditor使用及扩展
SharpDevelop (#develop)有很多“副产品”,其中最出名的应算SharpZipLib (#ziplib),纯C#的ZIP类库,而在SharpDevelop (#develop)中,“隐藏”了很多优秀的类库,其中ICSharpCode.TextEditor是表表者。
2519 0
|
6月前
|
C# Windows
ICSharpCode.SharpZipLib.Zip 解析时报错System.NotSupportedException: No data is available for encoding 936
​ 分析原因 利用ICSharpCode.SharpZipLib.Zip进行APK解析时,因为APK内编译的名称为中文,查询微软开发文档936为gb2312中文编码 [微软开发文档地址](https://docs.microsoft.com/zh-cn/windows/win32/intl/code-page-identifiers "微软开发文档地址") ```csharp // 错误代码 using (ZipInputStream zip = new ZipInputStream(File.OpenRead(path))) { using (var filestream = new
29 0
ICSharpCode.SharpZipLib.Zip 解析时报错System.NotSupportedException: No data is available for encoding 936
|
缓存 算法 C#
ICSharpCode.SharpZipLib 初级使用
ICSharpCode.SharpZipLib 初级使用
230 0
|
程序员 编译器 Linux
Unity与 DLL文件 ☀️| 什么是DLL✨?
📣前言 在之前的文章有介绍过so文件,那本篇文章就来介绍一些DLL文件吧! 提起DLL文件,大家肯定不会陌生,就算自己没编写生成过DLL文件,那也一定见过! Windows系统打开电脑C盘的System文件夹,往下一拉就会发现有超级多的带有.dll后缀的文件! 那DLL文件到底是个怎样的存在呢?本篇文章就来好好研究一下这个DLL文件究竟是个啥!
Unity与 DLL文件 ☀️| 什么是DLL✨?

热门文章

最新文章