已创建 Zip 但其中没有文件

Zip created but no files in it

有人可以告诉我我的代码有什么问题吗?我想将多个 xml 压缩到一个文件中,但结果文件总是空的。

using (MemoryStream zipStream = new MemoryStream())
{
    using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
    {

        string[] xmls = Directory.GetFiles(@"c:\temp\test", "*.xml");
        foreach (string xml in xmls)
        {
            var file = zip.CreateEntry(xml);
            using (var entryStream = file.Open())
            using (var streamWriter = new StreamWriter(entryStream))
            {
                streamWriter.Write(xml);
            }
        }
    }

    using (FileStream fs = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
    {
        zipStream.Position = 0;
        zipStream.CopyTo(fs);
    }
}

见备注in the documentation(强调我的):

The entryName string should reflect the relative path of the entry you want to create within the zip archive. There is no restriction on the string you provide. However, if it is not formatted as a relative path, the entry is created, but you may get an exception when you extract the contents of the zip archive. If an entry with the specified path and name already exists in the archive, a second entry is created with the same path and name.

您在这里使用的是绝对路径:

var file = zip.CreateEntry(xml);

我的猜测是,当您尝试打开存档时,它无法静默显示条目。

更改您的代码以使用不带路径的文件名:

var file = zip.CreateEntry(Path.GetFileName(xml));

作为一个单独的问题,请注意您只是将文件名写入 ZIP 条目,而不是实际文件。我想你想要这样的东西:

var zipEntry = zip.CreateEntry(Path.GetFileName(xml));
using (var entryStream = file.Open())
{
    using var fileStream = File.OpenRead(xml);
    fileStream.CopyTo(entryStream);
}