使用C#在Windows上调用7-zip解压文件

使用C#在Windows上调用7-zip解压文件

可以输入密码
可以省略输出的路径则默认创建压缩包同名文件夹

static void Main(string[] args){

            Console.WriteLine("你好,接下来开始解压文件");
             ExtractArchiveWithPassword(
               @"E:\压缩文件测试\压缩文件_Orgion\V_1696602827.7z",
                "",
                "123"
                );
}

        /// 
        /// 解压文件
        /// 
        /// 压缩文件的路径,需要有后缀
        /// 解压到的文件夹
        /// 压缩包密码
        public static void ExtractArchiveWithPassword(string archivePath, string outputDirectory = "'", string password = "")
        {
            // 7-Zip可执行文件的路径,根据你的安装路径进行修改
            string sevenZipExePath = @"C:\Program Files\7-Zip\7z.exe";

            if (outputDirectory == "")
            {
                outputDirectory = Path.Combine(Path.GetDirectoryName(archivePath), Path.GetFileNameWithoutExtension(archivePath));
            }


            // 构建解压命令行参数,包括密码参数
            string arguments = $"x \"{archivePath}\" -o\"{outputDirectory}\" -p{password}";

            // 创建一个新的进程来运行7-Zip
            Process process = new Process();
            process.StartInfo.FileName = sevenZipExePath;
            process.StartInfo.Arguments = arguments;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;

            // 启动7-Zip进程并等待其完成
            process.Start();
            process.WaitForExit();

            // 处理输出结果
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();

            if (string.IsNullOrEmpty(error))
            {
                // 解压成功
            }
            else
            {
                // 解压失败,错误信息在error变量中
            }
        }






你可能感兴趣的:(#,C#,c#,windows,7-zip)