.NET 使用7z压缩、解压文件

Nuget 搜索安装SevenZipSharp7z.Libs后,参考代码如下

7z 压缩文件

string sysBit = IntPtr.Size == 4 ? "x86" : "x64";
SevenZipBase.SetLibraryPath($@"{Environment.CurrentDirectory}\{sysBit}\7z.dll");
SevenZipCompressor compressor = new SevenZipCompressor();
compressor.CompressionFinished += (sender, e) =>
{
    Console.WriteLine("压缩完成");
};
compressor.CompressFiles(@"D:\work\工作杂项\数据库文件\sCTMS.7z", @"D:\work\工作杂项\数据库文件\sCTMS.bak");

7z 解压文件

string sysBit = IntPtr.Size == 4 ? "x86" : "x64";
SevenZipBase.SetLibraryPath($@"{Environment.CurrentDirectory}\{sysBit}\7z.dll");
SevenZipExtractor extractor = new SevenZipExtractor(@"D:\work\工作杂项\数据库文件\SQLPrompt_9.0.9.3951.7z");
extractor.FileExtractionFinished += (sender, e) =>
{
    Console.Clear();
    Console.WriteLine($"解压完成度:{e.PercentDone}%");
};
for (int i = 0; i < extractor.ArchiveFileData.Count; i++)
{
    extractor.ExtractFiles(@"D:\work\工作杂项\数据库文件\", extractor.ArchiveFileData[i].Index);
}

下面的别看了。

[Obsolete]

//要安装rx-main,否则就是用原生event处理
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Reactive.Linq;

namespace _7ZipTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "7ZipInstaller\\01.rar");
            //var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "7ZipInstaller\\02.7z");
            //var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "7ZipInstaller\\03.zip");
            var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "7ZipInstaller\\04.rar");
            try
            {
                Console.WriteLine("正在解压缩...\r\n");
                _7ZipHelper.UnZipFile(new FileInfo(filePath));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }            
            Console.Read();
        }
    }
    public class _7ZipHelper
    {
        /// <summary>
        /// 7Zip官网【https://www.7-zip.org/】下载的7z管理器安装程序
        /// </summary>
        private static string _7ZipExePath => ConfigurationManager.AppSettings[nameof(_7ZipExePath)];
        private static string _7UnZipPath => ConfigurationManager.AppSettings[nameof(_7UnZipPath)];

        /// <summary>
        /// 参数 【x】 从压缩文件中解压缩,包含目录结构 
        /// 解压缩c.7z到E:\Program Files: 
        /// 7z x c.7z -oE:\”Program Files” (-o表示输出目录,其与目录路径之间没有空格)这样解压包含下级目录名,
        /// 但不会在E:\Program Files下新建一个c文件夹,
        /// 如果需要,就把输出目录设为E:\Program Files\c,这样会自动创建文件夹c。
        /// </summary>
        /// <param name="fileInfo"></param>
        public static void UnZipFile(FileInfo fileInfo)
        {
            if (fileInfo.Exists)
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                Process process = new Process();
                process.EnableRaisingEvents = true;
                // 必须禁用操作系统外壳程序  
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardOutput = true;

                process.StartInfo.FileName = _7ZipExePath;
                process.StartInfo.Arguments = $@" x {fileInfo.FullName} -o{_7UnZipPath}\{Path.GetFileNameWithoutExtension(fileInfo.Name)}";
                process.Start();

                // 获取命令行内容  
                process.BeginOutputReadLine();
                //响应OutputDataReceived事件
                Observable.FromEventPattern<DataReceivedEventArgs>(process, nameof(process.OutputDataReceived))
                    .Where(t => !string.IsNullOrEmpty(t.EventArgs.Data))
                    .Subscribe(e =>
                    {
                        Console.WriteLine(e.EventArgs.Data);
                    });
                //7zip退出后执行事件
                Observable.FromEventPattern<EventArgs>(process, nameof(process.Exited))
                    .Subscribe(e =>
                    {
                        watch.Stop();
                        Console.WriteLine($"\r\n解压缩完成!耗时:{watch.ElapsedMilliseconds} (ms)");
                    });
            }
            else
            {
                Console.WriteLine($"未找到文件:【{fileInfo.FullName}】");
            }
        }
    }
}
[Obsolete]

posted @ 2019-01-31 11:26  xuxuzhaozhao  阅读(1324)  评论(0编辑  收藏  举报