在 ZipArchive class 中创建多个具有不同扩展名的 ZipArchiveEntry C#

Create multiple ZipArchiveEntry in ZipArchive class with different extensions C#

我正在尝试弄清楚如何创建包含具有不同扩展名的文件的 zip 存档,例如.txt 文件,.html 文件

如果我执行以下操作:

using (var zipArchive = new ZipArchive(memory, ZipArchiveMode.Create, true))
{
    var file1= zipArchive .CreateEntry("file1.html");
    var file2= zipArchive .CreateEntry("file2.txt");

    using (var entryStream = file1.Open())
    using (var sw = new StreamWriter(entryStream))
    {
        streamWriter.Write("testing testinsg steing");
    }

    using (var entryStream = file2.Open())
    using (var sw = new StreamWriter(entryStream))
    {
        sw.Write("xyxyxyxyxyxy");
    }
}

Entries in create mode may only be written to once, and only one entry may be held open at a time.

我该如何解决这个问题?

你只需要下线:

var file2= zipArchive .CreateEntry("file2.txt");

... 并将其放置在之后 你已经完成了对上一个条目的写入:

using (var zipArchive = new ZipArchive(memory, ZipArchiveMode.Create, true))
{
    var file1= zipArchive .CreateEntry("file1.html");

    using (var entryStream = file1.Open())
    using (var sw = new StreamWriter(entryStream))
    {
        streamWriter.Write("testing testinsg steing");
    }

    var file2= zipArchive .CreateEntry("file2.txt"); // <-- move this down
    using (var entryStream = file2.Open())
    using (var sw = new StreamWriter(entryStream))
    {
        sw.Write("xyxyxyxyxyxy");
    }
}