C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#压缩文件

C#在Windows上调用7-zip实现压缩文件

作者:先生沉默先

这篇文章主要为大家详细介绍了C#如何在Windows上调用7-zip实现压缩文件,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以学习一下

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

示例代码

using System;
using System.Diagnostics;

namespace 文件的压缩
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("你好,接下来开始压缩文件");

            ZipsHelper.CompressedInformation compressedInformation = new ZipsHelper.CompressedInformation(
               @"E:\压缩文件测试\压缩文件_Orgion\V_1696602827.txt",
               "",
                "",
               ZipsHelper.CompressedFileType.Zip,
               ZipsHelper.CompressedPackageEncryptionMode.AES256);
            //压缩  E:\压缩文件测试\压缩文件_Orgion\V1696602827.txt
            //到     E:\压缩文件测试\压缩文件_Orgion\V1696602827.zip

            ZipsHelper.DoCompressedFile(compressedInformation);

            Console.ReadKey();

        }
    }

    /// <summary>
    /// zip文件压缩
    /// </summary>
    public class ZipsHelper
    {

        /// <summary>
        /// 压缩文件
        /// </summary>
        public static void DoCompressedFile(CompressedInformation compressedInformation)
        {
            // 设置7-Zip可执行文件的路径,根据你的安装路径进行修改
            string sevenZipExePath = @"C:\Program Files\7-Zip\7z.exe";
            if (!System.IO.File.Exists(sevenZipExePath))
            {
                Console.WriteLine($"未能找到7z.exe ,请检查路径,当前路径是:{sevenZipExePath}");
                return;
            }
           if (compressedInformation.Password.Length > 98)
            {
                Console.WriteLine($"压缩取消,密码长度过长,最大长度是98,当前长度是:{compressedInformation.Password.Length}。");
                return;
            }
            string encryptionMethod;//压缩包的加密方式
            if (compressedInformation.CompressedPackageEncryptionMode == CompressedPackageEncryptionMode.AES256)
            {
                encryptionMethod = "-mem=AES256";
            }
            //else if (compressedInformation.CompressedPackageEncryptionMode == CompressedPackageEncryptionMode.LZMA)
            //{
            //encryptionMethod = "-mhe=on -m0=BCJ2 -m1=LZMA2 -m2=LZMA2 -m3=LZMA2 -mb0:1 -mb0s1:2 -mb0s2:3";
            //}
            else
            {
                encryptionMethod = "-mem=AES256";
            }

            string format;//设置压缩包的格式
            if (compressedInformation.CompressedFileType == CompressedFileType.Zip)
            {
                compressedInformation.CompressedFilePath += ".zip";//添加压缩包的文件后缀
                format = "zip";
            }
            else
            {
                format = "7z";
            }

            string arguments;//压缩的参数
            //构建7-Zip命令行参数 
            if (compressedInformation.Password == "")//当选择了压缩的加密方式但是密码为空的时候不能压缩
            {
                arguments = $"a -t{format} \"{compressedInformation.CompressedFilePath}\" \"{compressedInformation.FilePathToCompress}\"";
            }
            else
            {
                arguments = $"a -t{format} \"{compressedInformation.CompressedFilePath}\" \"{compressedInformation.FilePathToCompress}\" {encryptionMethod} -p{compressedInformation.Password}";
            }


            Console.WriteLine(arguments);

            // 创建一个新的进程来运行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))
            {
                Console.WriteLine("文件压缩成功!");
            }
            else
            {
                Console.WriteLine("文件压缩失败,错误信息:" + error);
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine(output);


        }


        /// <summary>
        /// 压缩包类型
        /// </summary>
        public enum CompressedFileType
        {
            Zip = 1,
            //  _7Z = 2

        }

        /// <summary>
        /// 压缩包加密格式
        /// </summary>
        public enum CompressedPackageEncryptionMode
        {
            AES256,
            //  LZMA,
        }


        public class CompressedInformation
        {
            /// <summary>
            /// 压缩文件路径
            /// </summary>
            private string filePathToCompress;

            /// <summary>
            /// 输出文件路径
            /// </summary>
            private string compressedFilePath;

            /// <summary>
            /// 密码
            /// </summary>
            private string password;

            /// <summary>
            /// 压缩包类型
            /// </summary>
            private CompressedFileType compressedFileType;


            /// <summary>
            ///  压缩包加密格式
            /// </summary>
            private CompressedPackageEncryptionMode compressedPackageEncryptionMode;

            public string FilePathToCompress { get => filePathToCompress; set => filePathToCompress = value; }
            public string CompressedFilePath { get => compressedFilePath; set => compressedFilePath = value; }
            public string Password { get => password; set => password = value; }
            public CompressedFileType CompressedFileType { get => compressedFileType; set => compressedFileType = value; }
            public CompressedPackageEncryptionMode CompressedPackageEncryptionMode { get => compressedPackageEncryptionMode; set => compressedPackageEncryptionMode = value; }

            /// <summary>
            /// 压缩命令参数
            /// </summary>
            /// <param name="filePathToCompress">压缩文件路径</param>
            /// <param name="compressedFilePath">压缩包输出路径</param>
            /// <param name="password">密码</param>
            /// <param name="compressedFileType">压缩包格式</param>
            /// <param name="compressedPackageEncryptionMode">压缩包加密方式</param>
            public CompressedInformation(string filePathToCompress,
                string compressedFilePath = "",
                string password = "",
                CompressedFileType compressedFileType = CompressedFileType.Zip,
                CompressedPackageEncryptionMode compressedPackageEncryptionMode = CompressedPackageEncryptionMode.AES256)
            {
                this.FilePathToCompress = filePathToCompress;
                this.CompressedFilePath = compressedFilePath;
                this.Password = password;
                this.CompressedFileType = compressedFileType;
                this.CompressedPackageEncryptionMode = compressedPackageEncryptionMode;

                if (compressedFilePath == "")
                {
                    GetFileNameAndExtension(filePathToCompress, out compressedFilePath);
                    this.CompressedFilePath = compressedFilePath;
                }
            }

            public static void GetFileNameAndExtension(string filePath, out string pathWithoutExtension)
            {
                pathWithoutExtension = System.IO.Path.ChangeExtension(filePath, null); // 去除文件后缀
            }


        }

    }

}

到此这篇关于C#在Windows上调用7-zip实现压缩文件的文章就介绍到这了,更多相关C#压缩文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文