2017-07-15 165 views
0

我試圖使用壓縮與DotNetZip此代碼2個PDF文件:壓縮PDF文件DotNetZip返回損壞的壓縮文件

void Main() 
{ 
    byte[] file1 = File.ReadAllBytes(@"C:\temp\a.pdf"); 
    byte[] file2 = File.ReadAllBytes(@"C:\temp\b.pdf"); 
    //byte[] file3 = File.ReadAllBytes(@"C:\temp\c.pdf"); 

    byte[] zip = Zipper.CreateZipFromFileContentList(new List<Tuple<string, byte[]>> { 
     new Tuple<string, byte[]>(@"a.pdf", file1), 
     new Tuple<string, byte[]>(@"b.pdf", file2)//, 
     //new Tuple<string, byte[]>(@"c.pdf", file3) 
    }); 
    File.WriteAllBytes(@"C:\temp\c.zip", zip); 

    using(Ionic.Zip.ZipFile zipFile = Ionic.Zip.ZipFile.Read(@"C:\temp\c.zip")) 
    { 
     foreach(ZipEntry entry in zipFile) 
     { 
      entry.Extract(@"C:\temp\t"); 
     } 
    } 
} 

// Define other methods and classes here 
static class Zipper 
{ 
    public static byte[] CreateZipFromFileContentList(IList<Tuple<string, byte[]>> fileContentList) 
    { 
     try 
     { 
      using (ZipFile zip = new ZipFile()) 
      { 
       int i = 0; 

       foreach (var item in fileContentList) 
       { 
        ZipEntry entry = null; 
        entry = zip.AddEntry(item.Item1, item.Item2); 
        ++i; 

       } 
       MemoryStream ms = new MemoryStream(); 
       zip.Save(ms); 
       return ms.GetBuffer(); 
      } 
     } 
     catch (Exception) 
     { 
      throw; 
     } 
    } 
} 

其實一切正常,因爲在創建歸檔後的提取過程的工作。但是,如果我嘗試使用winRar打開zip文件,則會收到一條消息,指出存檔已損壞。如果我嘗試使用7Zip,我會收到一條消息,指出有用數據塊的末尾有數據(翻譯後,我不知道英文版是否提供了完全相同的消息)。

如果我拉鍊1個或3個文件,我沒有問題的。 我該如何解決這個問題?

+0

你有使用普通的文本文件,嘗試這樣做?你能壓縮和解壓2個文本文件成功嗎? – rossum

+1

你的拉鍊產量可能有額外的字節,因爲.GetBuffer返回流內部緩衝區 - 僅包含有效的數據部分,使用.ToArray()代替。 –

+0

@AlexK。解決問題,請回答,我會接受它作爲正確的 – Phate01

回答

1

你的拉鍊產量可能有額外的字節,因爲.GetBuffer()返回流內部緩衝區 - 僅包含有效數據的一部分。

使用.ToArray()而不是將只返回緩衝區的使用的部分。