2011-10-28 198 views
0

我有一個Windows Phone應用程序。我正在使用SharpZipLib壓縮文件夾及其子文件夾。這只是壓縮文件夾,但文件夾內的數據沒有被壓縮。任何人都可以指導我如何做到這一點?如何在Silverlight中壓縮和解壓縮文件夾及其子文件夾?

我的代碼:

private void btnZip_Click(object sender, RoutedEventArgs e) 
    { 
     using (IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication()) 
     { 
      foreach (string filename in appStore.GetFileNames(directoryName + "/" + "*.txt")) 
      {     
       GetCompressedByteArray(filename); 
      } 
      textBlock2.Text = "Created file has Zipped Successfully"; 
     } 
    } 
public byte[] GetCompressedByteArray(string content) 
     { 
      byte[] compressedResult; 
      using (MemoryStream zippedMemoryStream = new MemoryStream()) 
      { 
       using (ZipOutputStream zipOutputStream = new ZipOutputStream(zippedMemoryStream)) 
       { 
        zipOutputStream.SetLevel(9); 
        byte[] buffer;     
        using (MemoryStream file = new MemoryStream(Encoding.UTF8.GetBytes(content))) 
        { 
         buffer = new byte[file.Length]; 
         file.Read(buffer, 0, buffer.Length); 
        }      
        ZipEntry entry = new ZipEntry(content); 
        zipOutputStream.PutNextEntry(entry); 
        zipOutputStream.Write(buffer, 0, buffer.Length); 
        zipOutputStream.Finish(); 
       } 
       compressedResult = zippedMemoryStream.ToArray(); 
      } 
      WriteToIsolatedStorage(compressedResult); 
      return compressedResult; 
     } 

     public void WriteToIsolatedStorage(byte[] compressedBytes) 
     { 
      IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication(); 
      appStore.CreateDirectory(ZipFolder); 
      using (IsolatedStorageFileStream zipTemplateStream = new IsolatedStorageFileStream(ZipFolder+"/"+directoryName + ".zip", FileMode.OpenOrCreate, appStore)) 
      using (BinaryWriter streamWriter = new BinaryWriter(zipTemplateStream)) 
      { 
       streamWriter.Write(compressedBytes); 
      } 
     } 
+0

還有另一個庫:http://dotnetzip.codeplex.com/。最終它與這個圖書館一起工作? –

+0

SharpZipLib無法實現嗎? – Shri

回答

1

我想你會發現this guide很有幫助。

從上述鏈接

zip文件對象提供了一個名爲AddDirectory(方法) 摘錄接受一個參數目錄名。這種方法的問題是 ,它不會將文件添加到指定的目錄中,但 只是在zip文件內創建一個目錄。要使此 正常工作,您需要通過循環訪問該目錄中的所有對象並逐個添加它們來獲取該目錄中的文件。我是 能夠通過創建一個遞歸函數來完成這個任務, 通過你想要的文件夾的整個目錄結構鑽取 zip。以下是該函數的一個片段。

我想你也面臨同樣的問題,即文件夾被添加到壓縮文件,但內容和子文件夾不壓縮。

希望這會有所幫助。

+0

@ Abhinav - 感謝您的回覆。我會試試這個。 – Shri

0

查看關於如何使用SharpZipLib壓縮包括嵌套文件夾的根文件夾的代碼示例over here