簡體   English   中英

C# - 如何使用 7-zip 庫(即不是 a.7z,而是.zip)創建常規 ZIP 存檔?

[英]C# - How do I create a regular ZIP archive using the 7-zip library(i.e. not a .7z, but .zip)?

這是我在這里的第一個問題,所以請耐心等待。

我的目標是在 C# 中創建一個 basic.zip 存檔。 我曾嘗試使用 .NET 的內置GZipStream class 並設法做到這一點,但我遇到的問題是我無法將文件命名為“usercode.zip”,而存檔文件不會丟失其擴展名。 由於限制,我無法讓我的程序將這些文件創建為“usercode.trf.zip”,這是我找到的將文件名的擴展名完整保留在存檔中的唯一方法。

我已經嘗試使用許多其他壓縮庫,但我似乎無法讓它們正常工作或按我想要的方式工作。

我遇到了SevenZipHelper庫,它提供了一些漂亮的函數來使用 LZMA(或 7-zip)庫來壓縮文件。

我正在使用的代碼如下所示:

//Take the BF file and zip it, using 7ZipHelper
BinaryReader bReader = new BinaryReader(File.Open(pFileName, FileMode.Open));
byte[] InBuf = new byte[Count];

bReader.Read(InBuf, 0, InBuf.Length);
Console.WriteLine("ZIP: read for buffer length:" + InBuf.Length.ToString());

byte[] OutBuf = SevenZip.Compression.LZMA.SevenZipHelper.Compress(InBuf);

FileStream BZipFile = new FileStream(pZipFileName, FileMode.OpenOrCreate, FileAccess.Write);
BZipFile.Seek(0, SeekOrigin.Begin);
BZipFile.Write(OutBuf, 0, OutBuf.Length);
BZipFile.Close();

這會使用 7-zip 算法巧妙地創建一個壓縮文件。 問題是我不能保證使用這個程序的客戶端可以訪問 7-zip,所以文件必須是正常的 zip 算法。 我已經瀏覽了 helper- 以及 7-zip 庫,似乎可以使用這個庫來使用普通的“ZIP”算法壓縮文件。 我似乎無法弄清楚如何做到這一點。 我注意到一些地方的屬性設置,但我找不到任何文檔或谷歌搜索告訴我在哪里設置它。

我意識到可能有更好的方法來做到這一點,而我只是錯過了一些東西,但我不能坐下來永遠為這樣一個本應簡單的任務而奮斗。 任何幫助將不勝感激。

如果你願意,你可以看看這個庫,我以前用過它,它使用起來非常簡單: dotnetzip

編輯(示例):

 using (ZipFile zip = new ZipFile())
        {
            foreach (String filename in FilesList)
            {
                Console.WriteLine("Adding {0}...", filename);
                ZipEntry e = zip.AddFile(filename,"");
                e.Comment = "file " +filename+" added "+DateTime.Now;
            }
            Console.WriteLine("Done adding files to zip:" + zipName);
            zip.Comment = String.Format("This zip archive was created by '{0}' on '{1}'",
               System.Net.Dns.GetHostName(), DateTime.Now);

            zip.Save(zipName);
            Console.WriteLine("Zip made:" + zipName);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM