簡體   English   中英

從文件創建內存zip

[英]Create in memory zip from a file

DeflateStream是否應該創建可以存儲為標准.zip存檔的存檔流?

我正在嘗試從本地文件創建內存中的zip(以遠程方式發送)。 我使用DeflateStream從本地磁盤上的文件獲取壓縮的字節數組:

public static byte[] ZipFile(string csvFullPath)
    {
        using (FileStream csvStream = File.Open(csvFullPath, FileMode.Open, FileAccess.Read))
        {
            using (MemoryStream compressStream = new MemoryStream())
            {
                using (DeflateStream deflateStream = new DeflateStream(compressStream, CompressionLevel.Optimal))
                {
                    csvStream.CopyTo(deflateStream);
                    deflateStream.Close();
                    return compressStream.ToArray();
                }
            }
        }
    }

這很好。 但是,當我將結果字節轉儲到zip文件中時:

byte[] zippedBytes = ZipFile(FileName);
File.WriteAllBytes("Sample.zip", zippedBytes);

我無法使用Windows內置.zip功能(或任何其他第三方存檔工具)打開生成的.zip存檔。

我現在正在計划使用ZipArchive,但是這需要在磁盤上創建臨時文件(首先將文件復制到單獨的目錄中,然后將其壓縮,然后將其讀入字節數組,然后將其刪除)

您可以使用這個漂亮的庫https://dotnetzip.codeplex.com/

或者您可以使用ZipArchive並與MemoryStream配合使用:

public static byte[] ZipFile(string csvFullPath)
{
    using (FileStream csvStream = File.Open(csvFullPath, FileMode.Open, FileAccess.Read))
    {
        using (MemoryStream zipToCreate = new MemoryStream())
        {
            using (ZipArchive archive = new ZipArchive(zipToCreate, ZipArchiveMode.Create, true))
            {
                ZipArchiveEntry fileEntry = archive.CreateEntry(Path.GetFileName(csvFullPath));
                using (var entryStream = fileEntry.Open())
                {
                    csvStream.CopyTo(entryStream);
                }
            }

            return zipToCreate.ToArray();
        }
    }
}

暫無
暫無

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

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