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

C# 解压缩文件

程序员文章站 2022-06-28 23:11:03
C# 解压缩文件 需要通过引用ICSharpCode.SharpZipLib.Zip(程序包里面下载安装),来实现文件的压缩与解压 /// /// 实例化FastZip /// public static FastZip fz = new FastZip() ......

c# 解压缩文件

 

需要通过引用icsharpcode.sharpziplib.zip(程序包里面下载安装),来实现文件的压缩与解压

/// <summary>
        /// 实例化fastzip
        /// </summary>
        public static fastzip fz = new fastzip();
/// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="zipfilepath">压缩文件的路径与名称</param>
        /// <param name="filepath">被压缩的文件路径</param>
        /// <param name="zippwd">解压密码(null代表无密码)</param>
        /// <returns></returns>
        public static string filetozip(string zipfilepath, string filepath, string zippwd)
        {
            string state = "fail...";
            try
            {
                fileinfo fi = new fileinfo(filepath);
                string filename = fi.name;
                string dirname = fi.directoryname;
                fz.password = zippwd;
                fz.createzip(zipfilepath, dirname, false, filename);

                state = "success !";
            }
            catch(exception ex)
            {
                state += "," + ex.message;
            }
            return state;
        }
/// <summary>
        /// 压缩文件夹
        /// </summary>
        /// <param name="dirpath">被压缩的文件夹路径</param>
        /// <param name="zippath">压缩文件夹的路径与名称</param>
        /// <param name="zippwd">解压密码(null代表无密码)</param>
        /// <returns></returns>
        public static string dirtozip(string dirpath, string zippath, string zippwd)
        {
            string state = "fail...";
            try
            {
                fz.password = zippwd;
                fz.createzip(zippath, dirpath, false, null);

                state = "success !";
            }
            catch (exception ex)
            {
                state += "," + ex.message;
            }
            return state;
        }
/// <summary>
        /// 解压zip
        /// </summary>
        /// <param name="dirpath">解压后存放路径</param>
        /// <param name="zippath">zip的存放路径</param>
        /// <param name="zippwd">解压密码(null代表无密码)</param>
        /// <returns></returns>
        public static string compress(string dirpath, string zippath, string zippwd)
        {
            string state = "fail...";
            try
            {
                fz.password = zippwd;
                fz.extractzip(zippath, dirpath, null);

                state = "success !";
            }
            catch (exception ex)
            {
                state += "," + ex.message;
            }
            return state;
        }