2016-06-08 90 views
0

我無法使用System.IO.Compression庫創建zip文件,然後返回該zip文件的byte []。所以我想讓該方法接受一個輸入字符串 - 要壓縮文件的路徑 - 並且在壓縮文件後返回文件的相應字節數組。目前,我可以將zip文件保存到一些已知路徑,然後使用System.IO.File.ReadAllBytes(path)獲取字節[]。System.IO:將zip文件轉換爲byte []而不保存文件

但是,如果我事先不知道該zip文件應該在哪裏結束(如果有的話),我該如何做到這一點?我在解決方案的嘗試如下。它似乎沒有工作,因爲當我嘗試從字節數組重新構建zip文件時,它表示存檔處於未知格式或已損壞。注意:我已經可以使用Ionic DotNetZip庫進行此操作了;不過,我試圖只使用System.IO庫來做同樣的事情。

關於如何去做這件事的任何想法?

private static byte[] CreateZipAndFindBytes(string importfile) 
{ 
    byte[] retVal = null; 

    using (System.IO.MemoryStream memStream = new System.IO.MemoryStream()) 
    { 
    //ZipArchive(Stream, ZipArchiveMode, Boolean) //true means leave stream open 
    using (System.IO.Compression.ZipArchive archive = new System.IO.Compression.ZipArchive(memStream, System.IO.Compression.ZipArchiveMode.Create, true)) 
    { 
     archive.CreateEntryFromFile(importfile, "test.zip"); //adds the file to the zip 
    } 
    retVal = memStream.ToArray(); 
    } 
    return retVal; 
} 

回答

0

entryNameCreateEntryFromFile第二個參數應該是「於zip存檔創建條目的名稱。」這不是你的zip文件的名字。

您正在壓縮導入文件,但也使用.zip擴展名重命名它,並且我假定導入文件實際上不是zip文件。

做到這一點,而不是

archive.CreateEntryFromFile(importfile, importfile); //adds the file to the zip 
+0

感謝。這解決了問題。 – Porter

+0

你知道這是否可以工作,如果該方法需要一個目錄作爲輸入?據我所知,CreateEntryFromFile在給定目錄而不是文件時不起作用 – Porter

+0

@Porter是否有一個名爲「CreateEntryFromDirectory」的方法? –

相關問題