簡體   English   中英

如何從C#內存中的文件創建ZipArchive?

[英]How to create ZipArchive from files in memory in C#?

是否有可能從內存中的文件創建ZipArchive(而不是實際在磁盤上)。

以下是用例:IEnumerable<HttpPostedFileBase>變量中接收多個文件。 我想使用ZipArchive將所有這些文件壓縮在一起。 問題是ZipArchive只允許CreateEntryFromFile ,它需要一個文件路徑,因為我只有內存中的文件。

問題:有沒有辦法在ZipArchive使用'stream'創建'entry',這樣我就可以直接在zip中輸入文件的內容?

我不想先保存文件,創建zip(從保存文件的路徑),然后刪除單個文件。

這里, attachmentFilesIEnumerable<HttpPostedFileBase>

using (var ms = new MemoryStream())
{
    using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
    {
        foreach (var attachment in attachmentFiles)
        {
            zipArchive.CreateEntryFromFile(Path.GetFullPath(attachment.FileName), Path.GetFileName(attachment.FileName),
                                CompressionLevel.Fastest);
        }
    }
    ...
}

是的,您可以使用ZipArchive.CreateEntry方法執行此操作,因為@AngeloReis在注釋中指出,並在此處描述了稍微不同的問題。

您的代碼將如下所示:

using (var ms = new MemoryStream())
{
    using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
    {
        foreach (var attachment in attachmentFiles)
        {
            var entry = zipArchive.CreateEntry(attachment.FileName, CompressionLevel.Fastest);
            using (var entryStream = entry.Open())
            {
                attachment.InputStream.CopyTo(entryStream);
            }
        }
    }
    ...
}

首先感謝@Alex的完美答案。
此外,對於您需要從文件系統中讀取的方案:

using (var ms = new MemoryStream())
{
    using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
    {
        foreach (var file in filesAddress)
        {
            zipArchive.CreateEntryFromFile(file, Path.GetFileName(file));
        }
    }

    ...
}

System.IO.Compression.ZipFileExtensions的幫助下

暫無
暫無

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

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