문제

C# 콘솔 애플리케이션에서 7 zip 아카이브를 어떻게 만들 수 있습니까? 일반적이고 광범위하게 사용할 수있는 아카이브를 추출 할 수 있어야합니다. 7-zip 프로그램.


이 질문에 대한 답으로 제공된 예제와 함께한 결과는 다음과 같습니다.

  • 7z.exe로 "Shelling" - 이것은 가장 단순하고 가장 효과적인 접근법이며, 나는 그것을 확인할 수 있습니다. 잘 작동합니다. 처럼 WorkMAD3 언급, 7z.exe가 모든 대상 기계에 설치되도록 보장하면됩니다. 이것이 제가 보장 할 수있는 것입니다.
  • 메모리 압축의 7zip - 이것은 클라이언트에게 보내기 전에 쿠키를 "메모리 내"압축하는 것을 말합니다. 이 방법은 다소 유망한 것 같습니다. 래퍼 메소드 (포장 LZMA SDK) 반환 유형 byte[]. 내가 쓸 때 byte[] 파일로 배열하면 7-zip을 사용하여 추출 할 수 없습니다.File.7z is not supported archive).
  • 7zsharp 래퍼 (CodePlex에서 발견) - 7Z Exe/LZMA SDK. 내 앱에서 프로젝트를 참조하고 일부 아카이브 파일을 성공적으로 만들었지 만 일반 7-ZIP 프로그램을 사용하여 파일을 추출 할 수 없었습니다.File.7z is not supported archive).
  • 7ZIP SDK 일명 LZMA SDK - 나는 이것을 사용하는 방법을 알아낼 수있을만큼 똑똑하지 않은 것 같아요 (이것이 여기에 게시 한 이유) ... 일반 7ZIP 프로그램에서 추출 할 수있는 7ZIP 아카이브 생성을 보여주는 작업 코드 예제는 무엇입니까?
  • 7-zip 아카이브 DLLS 용 CodeProject C# (.NET) 인터페이스 - 7ZIP 아카이브에서 추출을 지원합니다 ... 나는 그것들을 만들어야합니다!
  • Sharpziplib - 그들의 자주하는 질문, SharpZiplib는 7zip을 지원하지 않습니다.
도움이 되었습니까?

해결책

모든 대상 기계에 7-ZIP 앱이 설치 (및 경로)를 설치할 수 있으면 명령 줄 앱 7Z를 호출하여 오프로드 할 수 있습니다. 가장 우아한 솔루션은 아니지만 가장 적은 작업입니다.

다른 팁

Eggcafe 7zip 쿠키 예제 이것은 7ZIP의 DLL이있는 예 (Zipping Cookie)입니다.

코드 플렉스 래퍼이것은 7Z의 Zipping 함수를 뒤틀리는 오픈 소스 프로젝트입니다.

7ZIP SDK 7zip (C, C ++, C#, Java)의 공식 SDK <--- 내 제안

.NET Zip 라이브러리에 의해 SharpDevelop.net

CodeProject 7zip의 예제

Sharpziplib 많은 지핑

Sevenzipsharp 또 다른 해결책입니다. 7 zip 아카이브를 만듭니다 ...

다음은 C#에서 Sevenzip SDK를 사용하는 완전한 작업 예입니다.

Windows 7ZIP 응용 프로그램에서 작성한 표준 7ZIP 파일을 작성하고 읽습니다.

추신. 이전 예제는 파일의 시작에 필요한 속성 정보를 결코 쓰지 않았기 때문에 절대로 압축하지 않을 것입니다.

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");
        }
    }
}

SDK를 사용했습니다.

예 :

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();
      }
   }
}
 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\7-Zip\7zG.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) { }
        }

소스에서 7 지퍼를 설치하고 매개 변수를 메소드로 전달하십시오.

감사. 대답을 좋아하십시오.

이 코드를 사용합니다

                string PZipPath = @"C:\Program Files\7-Zip\7z.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();

가장 쉬운 방법은 .7z 대신 .zip 파일로 작업하고 사용하는 것입니다. 도트 넷 지퍼

7ZIP 명령을 쉘로 회전시킬 때 사용자 권한과 같은 다른 문제가 있습니다. 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

Sharpcompress 제 생각에는 가장 똑똑한 압축 라이브러리 중 하나입니다. LZMA (7-ZIP)를 지원하고 사용하기 쉽고 활발한 개발 중입니다.

LZMA 스트리밍 지원이 이미 있기 때문에 글을 쓰는 시점에서 불행히도 7-zip 아카이브 판독 값 만 지원합니다. 그러나 아카이브 쓰기는 TODO 목록에 있습니다 (ReadMe 참조). 향후 독자 : 현재 상태를 확인하십시오. https://github.com/adamhathcock/sharpcompress/blob/master/formats.md

호출 된 Nuget 패키지를 설치하십시오 SevenZipSharp.Interop

그 다음에:

SevenZipBase.SetLibraryPath(@".\x86\7z.dll");
var compressor = new SevenZip.SevenZipCompressor();
var filesToCompress = Directory.GetFiles(@"D:\data\");
compressor.CompressFiles(@"C:\archive\abc.7z", filesToCompress);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top