首页 > 编程语言 >C#通过7Z解压和压缩文件

C#通过7Z解压和压缩文件

时间:2024-08-11 10:25:11浏览次数:7  
标签:outSize string C# long 压缩文件 process doubleStream new 7Z

前言

在网络情况不够良好或者网速受限情况下,传输文件时,一般考虑使用压缩算法对文件进行压缩。7z压缩是一个压缩率比较高的软件,我们可以通过他来处理我们的文件。主要有两种方式进行压缩:方式1,直接通过调用库方式,可以在网上找到他的库算法;方式2,通过CMD命令行模式调用。

1、直接调用库

直接调用库,有一个好处是后期可控制性比较好,它还提供了一个处理回调函数。可以查看处理情况。但传递参数较多,需要好好研究研究。

        //文件压缩处理
        private void ProcessFileEncode(string inputName, string outputName)
        {
            Stream inStream = new FileStream(inputName, FileMode.Open, FileAccess.Read);

            FileStream outStream = new FileStream(outputName, FileMode.Create, FileAccess.Write);

            FileStream trainStream = null;
            Int32 dictionary = 1 << 23;

            Int32 posStateBits = 2;
            Int32 litContextBits = 3;
            Int32 litPosBits = 0;
            Int32 algorithm = 2;
            Int32 numFastBytes = 128;

            bool eos = true;

            CoderPropID[] propIDs =
            {
                    CoderPropID.DictionarySize,
                    CoderPropID.PosStateBits,
                    CoderPropID.LitContextBits,
                    CoderPropID.LitPosBits,
                    CoderPropID.Algorithm,
                    CoderPropID.NumFastBytes,
                    CoderPropID.MatchFinder,
                    CoderPropID.EndMarker
                };
            object[] properties =
            {
                    dictionary,
                    posStateBits,
                    litContextBits,
                    litPosBits,
                    algorithm,
                    numFastBytes,
                    "bt4",
                    eos
                };

            Encoder encoder = new Encoder();
            encoder.SetCoderProperties(propIDs, properties);
            encoder.WriteCoderProperties(outStream);
            Int64 fileSize = inStream.Length;
            for (int i = 0; i < 8; i++)
                outStream.WriteByte((Byte)(fileSize >> (8 * i)));
            if (trainStream != null)
            {
                CDoubleStream doubleStream = new CDoubleStream();
                doubleStream.s1 = trainStream;
                doubleStream.s2 = inStream;
                doubleStream.fileIndex = 0;
                inStream = doubleStream;
                long trainFileSize = trainStream.Length;
                doubleStream.skipSize = 0;
                if (trainFileSize > dictionary)
                    doubleStream.skipSize = trainFileSize - dictionary;
                trainStream.Seek(doubleStream.skipSize, SeekOrigin.Begin);
                encoder.SetTrainSize((uint)(trainFileSize - doubleStream.skipSize));
            }
            encoder.Code(inStream, outStream, -1, -1, proceCallInfo);
            outStream.Close();
            inStream.Close();
        }

        //文件解压处理
        private void ProcessFileDecode(string inputName, string outputName)
        {
            Stream inStream = new FileStream(inputName, FileMode.Open, FileAccess.Read);

            FileStream outStream = new FileStream(outputName, FileMode.Create, FileAccess.Write);

            byte[] properties = new byte[5];
            if (inStream.Read(properties, 0, 5) != 5)
                throw new Exception("input .lzma is too short");
            Decoder decoder = new Decoder();
            decoder.SetDecoderProperties(properties);

            long outSize = 0;
            for (int i = 0; i < 8; i++)
            {
                int v = inStream.ReadByte();
                if (v < 0)
                    throw new Exception("Can't Read 1");
                outSize |= ((long)(byte)v) << (8 * i);
            }
            long compressedSize = inStream.Length - inStream.Position;
            decoder.Code(inStream, outStream, compressedSize, outSize, proceCallInfo);
            outStream.Close();
            inStream.Close();
        }

处理信息


        public class ProceCallInfo : BindableBase, ICodeProgress
        {
            private long inSize;

            public long InSize
            {
                get { return inSize; }
                set { Set(ref inSize, value); }
            }

            private long outSize;

            public long OutSize
            {
                get { return outSize; }
                set { Set(ref outSize, value); OnPropertyChanged("Ration"); }
            }

            private string processRatio;

            public string ProcessRatio
            {
                get { return processRatio; }
                set { Set(ref processRatio, value); }
            }

            public double Ration
            {
                get
                {
                    if (outSize == 0 || InSize == 0)
                        return 0;
                    else
                        return outSize * 1.0 / InSize;
                }
            }

            public void SetProgress(long inSize, long outSize)
            {
                InSize = inSize;
                OutSize = outSize;
            }
        }

2、CMD间接方式

        /// <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();
        }

3、主调逻辑

压缩文件

        //压缩文件
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string OrgfilePath = @"D:\图像\123.tiff";
            string outfilePath = @"D:\图像\777.7z";
            WriteInfo("start Process!");
            Button btn = sender as Button;
            btn.IsEnabled = false;
            stopwatch.Restart();
            string path = @"C:\Program Files\7-Zip\7zg.exe";
            ZipHelper zipHelper = new ZipHelper(path);
            await Task.Run(() =>
            {
                // zipHelper.CompressFile(OrgfilePath,outfilePath);
                ProcessFileEncode(OrgfilePath, outfilePath);
            });
            stopwatch.Stop();
            WriteInfo($"End Process {stopwatch.ElapsedMilliseconds}ms!");
            btn.IsEnabled = true;
        }

解压文件

  private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            string OrgfilePath = @"D:\图像\777.7z";
            string outfilePath = @"D:\图像\777.tiff";
            WriteInfo("start Process!");
            Button btn = sender as Button;
            btn.IsEnabled = false;
            stopwatch.Restart();

            await Task.Run(() =>
            {
                // zipHelper.CompressDirectory(OrgfilePath, outfilePath);
                ProcessFileDecode(OrgfilePath, outfilePath);
            });

            stopwatch.Stop();
            WriteInfo($"End Process {stopwatch.ElapsedMilliseconds}ms!");
            btn.IsEnabled = true;
        }

标签:outSize,string,C#,long,压缩文件,process,doubleStream,new,7Z
From: https://blog.csdn.net/weixin_45114627/article/details/140927610

相关文章

  • 利用OpenCvSharp进行图像相关操作
    前言程序设计过程,有时也需要对图像进行一些简单操作,C#没有现成的图像处理库,但有人对OpenCV进行了包装,我们可以很方便的使用OpenCvSharp对图像进行操作。当然了,这也需要使用的人员进行一些研究,但相对于C++版本,它已经非常友好了。1、显示图像代码:privatevoidbutton1_Click(......
  • Windows11系统PerceptionDevice.dll文件丢失问题
    其实很多用户玩单机游戏或者安装软件的时候就出现过这种问题,如果是新手第一时间会认为是软件或游戏出错了,其实并不是这样,其主要原因就是你电脑系统的该dll文件丢失了或没有安装一些系统软件平台所需要的动态链接库,这时你可以下载这个PerceptionDevice.dll文件(挑选合适的版本文......
  • Docker移动数据目录
    生产环境规范部署docker#!/bin/bash#定义旧的和新的Docker数据目录old_dir="/var/lib/docker"new_dir="/data/docker"#确保脚本以root权限运行if["$(id-u)"!="0"];thenecho"这个脚本需要以root权限运行"1>&2exit1fi#......
  • BMC Genomics | 火龙果的转录组和代谢组分析揭示了果皮和果肉颜色形成的机制
    阐明火龙果果肉和果皮变色的候选基因和关键代谢产物,是培育具有优良新口味和高营养价值的火龙果的必要条件。在这里,使用转录组(RNA-Seq)和代谢组分析(UPLC-MS/MS)鉴定了属于两种不同量天尺属物种的三种火龙果的结构和调控基因以及与果皮和果肉颜色相关的关键代谢物。作者综合的转录......
  • 从Docker拉取镜像一直失败超时?这些解决方案帮你解决烦恼
    解决目前无法访问,超时连接方法解决方案1:配置加速地址配置加速地址:适用于Ubuntu16.04+、Debian8+、CentOS7+方式一:使用以下命令设置registrymirror:但是需要重启docker服务sudomkdir-p/etc/dockersudotee/etc/docker/daemon.json<<-'EOF'{"registry-mirrors":......
  • linux系统CENTOS 7安装docker
    前言:使用阿里云镜像,在CENTOS7版本上安装docker容器,方便使用docker容器安装其他软件。前置准备如果已经安装了docker,先将其卸载。yumremovedocker安装docker安装docker依赖的软件包。sudoyuminstall-yyum-utilsdevice-mapper-persistent-datalvm2添加阿里......
  • ABC 366E Manhattan Multifocal Ellipse
    题意给你N个在二位平面上的整点(即横纵坐标都为整数的点),以及一个距离阈值D,求有多少个整点(x,y)满足Σ(abs(x-x[i])+abs(y-y[i])),(1≤i≤N)思路题目显然是要要求某个点到给定的N个点的曼哈顿距离之和,但是如果强行枚举点,根据数据范围显然是不可以通过的。那么我们仔细思考一下......
  • ISO 26262中的失效率计算:IEC TR 62380-Section 18-Protection devices
    目录概要1元器件分类2失效率的计算2.1失效率预测模型2.2Base失效率的选取2.3λoverstress的计算2.3.1πI的选取2.3.2电过应力失效率的选取概要IECTR62380《电子组件、PCBs和设备的可靠性预计通用模型》是涵盖电路、半导体分立器件、光电组件、电阻器、电......
  • Cisco Firepower 4100 Series FTD Software 7.4.2 & ASA Software 9.20.3 发布下载 -
    CiscoFirepower4100SeriesFTDSoftware7.4.2&ASASoftware9.20.3发布下载-思科防火墙系统软件FirepowerThreatDefense(FTD)Software请访问原文链接:https://sysin.org/blog/cisco-firepower-4100/,查看最新版。原创作品,转载请保留出处。为什么选择CiscoSecure......
  • Cisco Firepower 2100 Series FTD Software 7.4.2 & ASA Software 9.20.3 发布下载 -
    CiscoFirepower2100SeriesFTDSoftware7.4.2&ASASoftware9.20.3发布下载-思科防火墙系统软件FirepowerThreatDefense(FTD)Software请访问原文链接:https://sysin.org/blog/cisco-firepower-2100/,查看最新版。原创作品,转载请保留出处。为什么选择CiscoSecure......