欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#工具类:使用SharpZipLib进行压缩、解压文件

程序员文章站 2022-05-26 23:46:50
SharpZipLib是一个开源的C#压缩解压库,应用非常广泛。就像用ADO.NET操作数据库要打开连接、执行命令、关闭连接等多个步骤一样,用SharpZipLib进行压缩和解压也需要多个步骤。SharpZipLib功能比较强大,在很多C#的应用中,都有它的身影,我们可以通过引入SharpZipLi ......

sharpziplib是一个开源的c#压缩解压库,应用非常广泛。就像用ado.net操作数据库要打开连接、执行命令、关闭连接等多个步骤一样,用sharpziplib进行压缩和解压也需要多个步骤。sharpziplib功能比较强大,在很多c#的应用中,都有它的身影,我们可以通过引入sharpziplib类库文件,在程序中实现自动压缩文件以及解压缩文件的功能,例如一个常见的情景就是用户客户端程序下载更新包,下载完成之后,在本地自动解压文件。

  sharpziplib的官方地址是:http://icsharpcode.github.io/sharpziplib/,实际使用可以通过nuget获取,在nuget的地址是:http://www.nuget.org/packages/sharpziplib/

在这个封装好的解压缩工具类中,我们引用了sharpziplib组件,实现了解压缩.zip文件格式的压缩文件,允许指定解压缩的路径。具体实现如下:

 public class sharpzip
    {
        public sharpzip()
        { }
        /// <summary>
        /// 压缩
        /// </summary> 
        /// <param name="filename"> 压缩后的文件名(包含物理路径)</param>
        /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
        public static void packfiles(string filename, string directory)
        {
            try
            {
                fastzip fz = new fastzip();
                fz.createemptydirectories = true;
                fz.createzip(filename, directory, true, "");
                fz = null;
            }
            catch (exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 解压缩
        /// </summary>
        /// <param name="file">待解压文件名(包含物理路径)</param>
        /// <param name="dir"> 解压到哪个目录中(包含物理路径)</param>
        public static bool unpackfiles(string file, string dir)
        {
            try
            {
                if (!directory.exists(dir))
                {
                    directory.createdirectory(dir);
                }
                zipinputstream s = new zipinputstream(file.openread(file));
                zipentry theentry;
                while ((theentry = s.getnextentry()) != null)
                {
                    string directoryname = path.getdirectoryname(theentry.name);
                    string filename = path.getfilename(theentry.name);
                    if (directoryname != string.empty)
                    {
                        directory.createdirectory(dir + directoryname);
                    }
                    if (filename != string.empty)
                    {
                        filestream streamwriter = file.create(dir + theentry.name);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.read(data, 0, data.length);
                            if (size > 0)
                            {
                                streamwriter.write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                        streamwriter.close();
                    }
                }
                s.close();
                return true;
            }
            catch (exception)
            {
                throw;
            }
        }
    }
    public class classzip
    {
        #region 私有方法
        /// <summary>
        /// 递归压缩文件夹方法
        /// </summary>
        private static bool zipfiledictory(string foldertozip, zipoutputstream s, string parentfoldername)
        {
            bool res = true;
            string[] folders, filenames;
            zipentry entry = null;
            filestream fs = null;
            crc32 crc = new crc32();
            try
            {
                entry = new zipentry(path.combine(parentfoldername, path.getfilename(foldertozip) + "/"));
                s.putnextentry(entry);
                s.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;
                    s.putnextentry(entry);
                    s.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, s, path.combine(parentfoldername, path.getfilename(foldertozip))))
                {
                    return false;
                }
            }
            return res;
        }
        /// <summary>
        /// 压缩目录
        /// </summary>
        /// <param name="foldertozip">待压缩的文件夹,全路径格式</param>
        /// <param name="zipedfile">压缩后的文件名,全路径格式</param>
        private static bool zipfiledictory(string foldertozip, string zipedfile, int level)
        {
            bool res;
            if (!directory.exists(foldertozip))
            {
                return false;
            }
            zipoutputstream s = new zipoutputstream(file.create(zipedfile));
            s.setlevel(level);
            res = zipfiledictory(foldertozip, s, "");
            s.finish();
            s.close();
            return res;
        }
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="filetozip">要进行压缩的文件名</param>
        /// <param name="zipedfile">压缩后生成的压缩文件名</param>
        private static bool zipfile(string filetozip, string zipedfile, int level)
        {
            if (!file.exists(filetozip))
            {
                throw new system.io.filenotfoundexception("指定要压缩的文件: " + filetozip + " 不存在!");
            }
            filestream zipfile = null;
            zipoutputstream zipstream = null;
            zipentry zipentry = null;
            bool res = true;
            try
            {
                zipfile = file.openread(filetozip);
                byte[] buffer = new byte[zipfile.length];
                zipfile.read(buffer, 0, buffer.length);
                zipfile.close();
                zipfile = file.create(zipedfile);
                zipstream = new zipoutputstream(zipfile);
                zipentry = new zipentry(path.getfilename(filetozip));
                zipstream.putnextentry(zipentry);
                zipstream.setlevel(level);
                zipstream.write(buffer, 0, buffer.length);
            }
            catch
            {
                res = false;
            }
            finally
            {
                if (zipentry != null)
                {
                    zipentry = null;
                }
                if (zipstream != null)
                {
                    zipstream.finish();
                    zipstream.close();
                }
                if (zipfile != null)
                {
                    zipfile.close();
                    zipfile = null;
                }
                gc.collect();
                gc.collect(1);
            }
            return res;
        }
        #endregion
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="filetozip">待压缩的文件目录</param>
        /// <param name="zipedfile">生成的目标文件</param>
        /// <param name="level">6</param>
        public static bool zip(string filetozip, string zipedfile, int level)
        {
            if (directory.exists(filetozip))
            {
                return zipfiledictory(filetozip, zipedfile, level);
            }
            else if (file.exists(filetozip))
            {
                return zipfile(filetozip, zipedfile, level);
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="filetoupzip">待解压的文件</param>
        /// <param name="zipedfolder">解压目标存放目录</param>
        public static void unzip(string filetoupzip, string zipedfolder)
        {
            if (!file.exists(filetoupzip))
            {
                return;
            }
            if (!directory.exists(zipedfolder))
            {
                directory.createdirectory(zipedfolder);
            }
            zipinputstream s = null;
            zipentry theentry = null;
            string filename;
            filestream streamwriter = null;
            try
            {
                s = new zipinputstream(file.openread(filetoupzip));
                while ((theentry = s.getnextentry()) != null)
                {
                    if (theentry.name != string.empty)
                    {
                        filename = path.combine(zipedfolder, theentry.name);
                        if (filename.endswith("/") || filename.endswith("\\"))
                        {
                            directory.createdirectory(filename);
                            continue;
                        }
                        streamwriter = file.create(filename);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.read(data, 0, data.length);
                            if (size > 0)
                            {
                                streamwriter.write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (streamwriter != null)
                {
                    streamwriter.close();
                    streamwriter = null;
                }
                if (theentry != null)
                {
                    theentry = null;
                }
                if (s != null)
                {
                    s.close();
                    s = null;
                }
                gc.collect();
                gc.collect(1);
            }
        }
    }
    public class ziphelper
    {
        #region 私有变量
        string the_rar;
        registrykey the_reg;
        object the_obj;
        string the_info;
        processstartinfo the_startinfo;
        process the_process;
        #endregion
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="zipname">要解压的文件名</param>
        /// <param name="zippath">要压缩的文件目录</param>
        /// <param name="dirpath">初始目录</param>
        public void enzip(string zipname, string zippath, string dirpath)
        {
            try
            {
                the_reg = registry.classesroot.opensubkey(@"applications\winrar.exe\shell\open\command");
                the_obj = the_reg.getvalue("");
                the_rar = the_obj.tostring();
                the_reg.close();
                the_rar = the_rar.substring(1, the_rar.length - 7);
                the_info = " a    " + zipname + "  " + zippath;
                the_startinfo = new processstartinfo();
                the_startinfo.filename = the_rar;
                the_startinfo.arguments = the_info;
                the_startinfo.windowstyle = processwindowstyle.hidden;
                the_startinfo.workingdirectory = dirpath;
                the_process = new process();
                the_process.startinfo = the_startinfo;
                the_process.start();
            }
            catch (exception ex)
            {
                throw new exception(ex.message);
            }
        }
        /// <summary>
        /// 解压缩
        /// </summary>
        /// <param name="zipname">要解压的文件名</param>
        /// <param name="zippath">要解压的文件路径</param>
        public void dezip(string zipname, string zippath)
        {
            try
            {
                the_reg = registry.classesroot.opensubkey(@"applications\winrar.exe\shell\open\command");
                the_obj = the_reg.getvalue("");
                the_rar = the_obj.tostring();
                the_reg.close();
                the_rar = the_rar.substring(1, the_rar.length - 7);
                the_info = " x " + zipname + " " + zippath;
                the_startinfo = new processstartinfo();
                the_startinfo.filename = the_rar;
                the_startinfo.arguments = the_info;
                the_startinfo.windowstyle = processwindowstyle.hidden;
                the_process = new process();
                the_process.startinfo = the_startinfo;
                the_process.start();
            }
            catch (exception ex)
            {
                throw new exception(ex.message);
            }
        }
    }

 

扩展阅读:c#工具类:使用itextsharp操作pdf文档。 

备注:此文章转载自博主个人技术站点:it技术小趣屋。原文链接:查看原文