我無法使用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;
}
感謝。這解決了問題。 – Porter
你知道這是否可以工作,如果該方法需要一個目錄作爲輸入?據我所知,CreateEntryFromFile在給定目錄而不是文件時不起作用 – Porter
@Porter是否有一個名爲「CreateEntryFromDirectory」的方法? –