C# 如何使用 .NET 创建 7-Zip 档案?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/222030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:44:21  来源:igfitidea点击:

How do I create 7-Zip archives with .NET?

c#.netcompression7zip

提问by Seibar

How can I create 7-Zip archives from my C# console application? I need to be able to extract the archives using the regular, widely available 7-Zipprogram.

如何从我的 C# 控制台应用程序创建 7-Zip 档案?我需要能够使用常规的、广泛使用的7-Zip程序提取档案。



Here are my results with the examples provided as answers to this question

以下是我提供的示例的结果,作为此问题的答案

  • "Shelling out" to 7z.exe - this is the simplest and most effective approach, and I can confirm that it works nicely. As workmad3 mentions, I just need to guarantee that 7z.exe is installed on all target machines, which is something I can guarantee.
  • 7Zip in memory compression- this refers to compressing cookies "in-memory" before sending to the client; this method seems somewhat promising. The wrapper methods (wrapping the LZMA SDK) return type byte[]. When I write the byte[]array to a file, I can't extract it using 7-Zip (File.7z is not supported archive).
  • 7zSharpWrapper (found on CodePlex) - this wraps the 7z exe/LZMA SDK. I referenced the project from my app, and it successfully created some archive files, but I was unable to extract the files using the regular 7-Zip program (File.7z is not supported archive).
  • 7Zip SDK aka LZMA SDK- I guess I'm not smart enough to figure out how to use this (which is why I posted here)... Any working code examples that demonstrate creating a 7zip archive that is able to be extracted by the regular 7zip program?
  • CodeProject C# (.NET) Interface for 7-Zip Archive DLLs- only supports extracting from 7zip archives... I need to create them!
  • SharpZipLib- According to their FAQ, SharpZipLib doesn't support 7zip.
  • “脱壳”到 7z.exe - 这是最简单和最有效的方法,我可以确认它运行良好。正如workmad3提到的,我只需要保证7z.exe安装在所有目标机器上,这是我可以保证的。
  • 7Zip 内存压缩- 这是指在发送到客户端之前压缩“内存中”cookie;这种方法似乎有些有希望。包装方法(包装LZMA SDK)返回类型byte[]。当我将byte[]数组写入文件时,我无法使用 7-Zip ( File.7z is not supported archive)提取它。
  • 7zSharpWrapper(可在 CodePlex 上找到)- 包装 7z exe/ LZMA SDK。我从我的应用程序中引用了该项目,它成功创建了一些存档文件,但我无法使用常规 7-Zip 程序 ( File.7z is not supported archive)提取文件。
  • 7Zip SDK 又名 LZMA SDK- 我想我不够聪明,无法弄清楚如何使用它(这就是我在这里发布的原因)...任何演示创建 7zip 存档的工作代码示例,该存档可以由常规的 7zip 程序?
  • 用于 7-Zip 存档 DLL 的 CodeProject C# (.NET) 接口- 仅支持从 7zip 存档中提取...我需要创建它们!
  • SharpZipLib- 根据他们的常见问题解答,SharpZipLib 不支持 7zip。

采纳答案by workmad3

If you can guarantee the 7-zip app will be installed (and in the path) on all target machines, you can offload by calling the command line app 7z. Not the most elegant solution but it is the least work.

如果您可以保证 7-zip 应用程序将安装(并在路径中)在所有目标机器上,您可以通过调用命令行应用程序 7z 来卸载。不是最优雅的解决方案,但它是最少的工作。

回答by Patrick Desjardins

EggCafe 7Zip cookie exampleThis is an example (zipping cookie) with the DLL of 7Zip.

EggCafe 7Zip cookie 示例这是一个带有 7Zip DLL 的示例(压缩 cookie)。

CodePlex WrapperThis is an open source project that warp zipping function of 7z.

CodePlex Wrapper这是一个开源项目,可以对 7z 的压缩功能进行压缩。

7Zip SDKThe official SDK for 7zip (C, C++, C#, Java) <---My suggestion

7Zip SDK7zip 官方 SDK (C, C++, C#, Java) <---我的建议

.Net zip library by SharpDevelop.net

SharpDevelop.net 的.Net zip 库

CodeProjectexample with 7zip

带有 7zip 的CodeProject示例

SharpZipLibMany zipping

SharpZipLib许多压缩

回答by WOPR

I used the sdk.

我用的是sdk。

eg:

例如:

using SevenZip.Compression.LZMA;
private static void CompressFileLZMA(string inFile, string outFile)
{
   SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();

   using (FileStream input = new FileStream(inFile, FileMode.Open))
   {
      using (FileStream output = new FileStream(outFile, FileMode.Create))
      {
          coder.Code(input, output, -1, -1, null);
          output.Flush();
      }
   }
}

回答by markhor

SevenZipSharpis another solution. Creates 7-zip archives...

SevenZipSharp是另一种解决方案。创建 7-zip 档案...

回答by Orwellophile

Here's a complete working example using the SevenZip SDK in C#.

这是使用 C# 中的 SevenZip SDK 的完整工作示例。

It will write, and read, standard 7zip files as created by the Windows 7zip application.

它将写入和读取由 Windows 7zip 应用程序创建的标准 7zip 文件。

PS. The previous example was never going to decompress because it never wrote the required property information to the start of the file.

附注。前面的示例永远不会解压缩,因为它从未将所需的属性信息写入文件的开头。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SevenZip.Compression.LZMA;
using System.IO;
using SevenZip;

namespace VHD_Director
{
    class My7Zip
    {
        public static void CompressFileLZMA(string inFile, string outFile)
        {
            Int32 dictionary = 1 << 23;
            Int32 posStateBits = 2;
            Int32 litContextBits = 3; // for normal files
            // UInt32 litContextBits = 0; // for 32-bit data
            Int32 litPosBits = 0;
            // UInt32 litPosBits = 2; // for 32-bit data
            Int32 algorithm = 2;
            Int32 numFastBytes = 128;

            string mf = "bt4";
            bool eos = true;
            bool stdInMode = false;


            CoderPropID[] propIDs =  {
                CoderPropID.DictionarySize,
                CoderPropID.PosStateBits,
                CoderPropID.LitContextBits,
                CoderPropID.LitPosBits,
                CoderPropID.Algorithm,
                CoderPropID.NumFastBytes,
                CoderPropID.MatchFinder,
                CoderPropID.EndMarker
            };

            object[] properties = {
                (Int32)(dictionary),
                (Int32)(posStateBits),
                (Int32)(litContextBits),
                (Int32)(litPosBits),
                (Int32)(algorithm),
                (Int32)(numFastBytes),
                mf,
                eos
            };

            using (FileStream inStream = new FileStream(inFile, FileMode.Open))
            {
                using (FileStream outStream = new FileStream(outFile, FileMode.Create))
                {
                    SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder();
                    encoder.SetCoderProperties(propIDs, properties);
                    encoder.WriteCoderProperties(outStream);
                    Int64 fileSize;
                    if (eos || stdInMode)
                        fileSize = -1;
                    else
                        fileSize = inStream.Length;
                    for (int i = 0; i < 8; i++)
                        outStream.WriteByte((Byte)(fileSize >> (8 * i)));
                    encoder.Code(inStream, outStream, -1, -1, null);
                }
            }

        }

        public static void DecompressFileLZMA(string inFile, string outFile)
        {
            using (FileStream input = new FileStream(inFile, FileMode.Open))
            {
                using (FileStream output = new FileStream(outFile, FileMode.Create))
                {
                    SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder();

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

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

                    decoder.Code(input, output, compressedSize, outSize, null);
                }
            }
        }

        public static void Test()
        {
            CompressFileLZMA("DiscUtils.pdb", "DiscUtils.pdb.7z");
            DecompressFileLZMA("DiscUtils.pdb.7z", "DiscUtils.pdb2");
        }
    }
}

回答by lifestylebyatom

I use this code

我用这个代码

                string PZipPath = @"C:\Program Files-Zipz.exe";
                string sourceCompressDir = @"C:\Test";
                string targetCompressName = @"C:\Test\abc.zip";
                string CompressName = targetCompressName.Split('\').Last();
                string[] fileCompressList = Directory.GetFiles(sourceCompressDir, "*.*");

                    if (fileCompressList.Length == 0)
                    {
                        MessageBox.Show("No file in directory", "Important Message");
                        return;
                    }
                    string filetozip = null;
                    foreach (string filename in fileCompressList)
                    {
                        filetozip = filetozip + "\"" + filename + " ";
                    }

                    ProcessStartInfo pCompress = new ProcessStartInfo();
                    pCompress.FileName = PZipPath;
                    if (chkRequestPWD.Checked == true)
                    {
                        pCompress.Arguments = "a -tzip \"" + targetCompressName + "\" " + filetozip + " -mx=9" + " -p" + tbPassword.Text;
                    }
                    else
                    {
                        pCompress.Arguments = "a -tzip \"" + targetCompressName + "\" \"" + filetozip + "\" -mx=9";
                    }
                    pCompress.WindowStyle = ProcessWindowStyle.Hidden;
                    Process x = Process.Start(pCompress);
                    x.WaitForExit();

回答by Vishal Sen

 string zipfile = @"E:\Folderx\NPPES.zip";
 string folder = @"E:\TargetFolderx";

 ExtractFile(zipfile,folder);
public void ExtractFile(string source, string destination)
        {
            // If the directory doesn't exist, create it.
            if (!Directory.Exists(destination))
                Directory.CreateDirectory(destination);

            //string zPath = ConfigurationManager.AppSettings["FileExtactorEXE"];
          //  string zPath = Properties.Settings.Default.FileExtactorEXE; ;

            string zPath=@"C:\Program Files-ZipzG.exe";

            try
            {
                ProcessStartInfo pro = new ProcessStartInfo();
                pro.WindowStyle = ProcessWindowStyle.Hidden;
                pro.FileName = zPath;
                pro.Arguments = "x \"" + source + "\" -o" + destination;
                Process x = Process.Start(pro);
                x.WaitForExit();
            }
            catch (System.Exception Ex) { }
        }

Just Install 7 zip from source and pass the parameter to the method.

只需从源安装 7 zip 并将参数传递给方法。

Thanks. Please like the answer.

谢谢。请喜欢答案。

回答by Brent

These easiest way is to work with .zip files instead of .7z and use Dot Net Zip

这些最简单的方法是使用 .zip 文件而不是 .7z 并使用Dot Net Zip

When spinning off 7zip commands to shell there are other issues like user privileges, I had issue with SevenZipSharp.

当将 7zip 命令分拆到 shell 时,还有其他问题,例如用户权限,我遇到了 SevenZipSharp 问题。

Private Function CompressFile(filename As String) As Boolean
Using zip As New ZipFile()
    zip.AddFile(filename & ".txt", "")
    zip.Save(filename & ".zip")
End Using

Return File.Exists(filename & ".zip")
End Function

回答by Mario Eis

SharpCompressis in my opinion one of the smartest compression libraries out there. It supports LZMA (7-zip), is easy to use and under active development.

在我看来,SharpCompress是最智能的压缩库之一。它支持 LZMA (7-zip),易于使用且正在积极开发中。

As it has LZMA streaming support already, at the time of writing it unfortunately only supports 7-zip archive reading. BUT archive writing is on their todo list (see readme). For future readers: Check to get the current status here: https://github.com/adamhathcock/sharpcompress/blob/master/FORMATS.md

由于它已经支持 LZMA 流媒体,因此在撰写本文时,它仅支持 7-zip 存档读取。但是存档写入在他们的待办事项列表中(请参阅自述文件)。对于未来的读者:在此处查看当前状态:https: //github.com/adamhathcock/sharpcompress/blob/master/FORMATS.md

回答by Fidel

Install the NuGet package called SevenZipSharp.Interop

安装名为的 NuGet 包 SevenZipSharp.Interop

Then:

然后:

SevenZipBase.SetLibraryPath(@".\x86z.dll");
var compressor = new SevenZip.SevenZipCompressor();
var filesToCompress = Directory.GetFiles(@"D:\data\");
compressor.CompressFiles(@"C:\archive\abc.7z", filesToCompress);