c#调用7z压缩和解压缩文件

来源:互联网 发布:恒腾网络 福利待遇 编辑:程序博客网 时间:2024/04/30 09:12

1.首先需要下载7z.exe,可以通过安装7-zip;

2.在安装目录下找到7z.exe,拷贝到自己的程序目录下;


整理的一个帮助类,代码如下:

    public class ZipHelper    {        // Fields        private string _7zInstallPath = @"C:\Program Files\7-Zip\7za.exe";        // Methods        public ZipHelper(string str7zInstallPath)        {            this._7zInstallPath = str7zInstallPath;        }        /// <summary>        /// 压缩文件夹目录        /// </summary>        /// <param name="strInDirectoryPath">指定需要压缩的目录,如C:\test\,将压缩test目录下的所有文件</param>        /// <param name="strOutFilePath">压缩后压缩文件的存放目录</param>        public void CompressDirectory(string strInDirectoryPath, string strOutFilePath)        {            Process process = new Process();            process.StartInfo.FileName = this._7zInstallPath;            process.StartInfo.Arguments = " a -t7z " + strOutFilePath + " " + strInDirectoryPath + " -r";            //隐藏DOS窗口            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;            process.Start();            process.WaitForExit();            process.Close();        }        /// <summary>        /// 压缩文件        /// </summary>        /// <param name="strInFilePath">指定需要压缩的文件,如C:\test\demo.xlsx,将压缩demo.xlsx文件</param>        /// <param name="strOutFilePath">压缩后压缩文件的存放目录</param>        public void CompressFile(string strInFilePath, string strOutFilePath)        {            Process process = new Process();            process.StartInfo.FileName = this._7zInstallPath;            process.StartInfo.Arguments = " a -t7z " + strOutFilePath + " " + strInFilePath + "";            //隐藏DOS窗口            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;            process.Start();            process.WaitForExit();            process.Close();        }        /// <summary>        /// 解压缩        /// </summary>        /// <param name="strInFilePath">压缩文件的路径</param>        /// <param name="strOutDirectoryPath">解压缩后文件的路径</param>        public void DecompressFileToDestDirectory(string strInFilePath, string strOutDirectoryPath)        {            Process process = new Process();            process.StartInfo.FileName = this._7zInstallPath;            process.StartInfo.Arguments = " x " + strInFilePath + " -o" + strOutDirectoryPath + " -r ";            //隐藏DOS窗口            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;            process.Start();            process.WaitForExit();            process.Close();        }    }


这里只是调用了几个很简单的命令,还有很多丰富的命名有兴趣可以去研究下:

http://blog.csdn.net/wbloveilove/article/details/7912438


注意,在调用-t7z命令进行文件压缩时,会在Mac上出现zip-->cpgz-->zip......无限循环的情况,



为了兼容性广泛一点,可以讲-t7z改为-tzip,这样当在服务器上压缩好文件,下载到Mac上时,就不会出现zip-->cpgz无限循环的情况了。




原创粉丝点击