C#调用7z实现文件的压缩与解压
1.关于7z
首先在这里先介绍一下7z压缩软件,7z是一种主流的 压缩格式,它拥有极高的压缩比。在计算机科学中,7z是一种可以使用多种压缩算法进行数据压缩的档案格式。主要有以下特点:
- 来源且模块化的组件结构
- 最高的压缩比
- 强大的AES-256加密
- 可更改配置的压缩算法
- 支持操大文件
- 支持多线程压缩
- 具有多种压缩文件格式
2.解压缩实现代码
实现对文件的解压缩方法是通过cmd命令,调用7z程式通过cmd命令实现对文件进行解压和压缩的操作,具体实现代码如下:
- 压缩代码
public object CompressZipFile(string sourceFile, string destinationFile) { object resObj; Process process = new Process(); string tempDestinationFile = ""; try { if (process == null) { process = new Process(); } tempDestinationFile = destinationFile.ToLower().EndsWith(".zip") ? destinationFile : destinationFile + ".zip"; process.StartInfo.FileName = "cmd.exe"; string command1 = @"cd c:\progra~1\7-zip"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.Start(); process.StandardInput.WriteLine(@"c:"); process.StandardInput.WriteLine(@"cd\"); process.StandardInput.WriteLine(command1); process.StandardInput.WriteLine(@"7Z a -tzip " + destinationFile + " " + sourceFile); process.StandardInput.WriteLine("exit"); string output = process.StandardOutput.ReadToEnd(); if (output.ToUpper().IndexOf("EVERYTHING IS OK") > -1) { resObj = new object[] { 0, "Compress file[" + destinationFile + "] OK!" }; } else { resObj = new object[] { 1, "Compress File[" + destinationFile + "] Error!" }; } } catch (Exception ex) { resObj = new object[] { 1, "Compress File[" + destinationFile + "] exception:" + ex.Message }; } return resObj; }
- 解压代码
public object decompressFile(string zipFilepath, string FileDir) { object resObj; try { string batfiledata = @"c:\progra~1\7-zip\7z.exe x " + zipFilepath + " -o" + FileDir + " -y"; Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = "/c " + batfiledata; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.Start(); string output = process.StandardOutput.ReadToEnd(); if (output.ToUpper().IndexOf("EVERYTHING IS OK") > -1) { resObj = new object[] { 0, "DeCompress file[" + zipFilepath + "] OK!" }; } else { resObj = new object[] { 1, "DeCompress File[" + zipFilepath + "] Error!" }; } } catch (Exception ex) { resObj = new object[] { 1, ex.Message }; } return resObj; }