SharpZipLib - 将 ZipEntry 添加到 ZipFile 会引发 ZipException

SharpZipLib - adding a ZipEntry to a ZipFile throws a ZipException

我正在尝试使用内存字符串中的文件创建 ZIP 文件并保存。到目前为止,这是我的代码:

var zip = ZipFile.Create(Path.Combine(outputPath, fileName));
zip.BeginUpdate();

var fileStream = new MemoryStream(Encoding.Default.GetBytes(myStringVariable));
var outputMemStream = new MemoryStream();
var zipStream = new ZipOutputStream(outputMemStream);
var zipEntry = new ZipEntry("file.html");

zipEntry.DateTime = DateTime.Now;
zipStream.PutNextEntry(zipEntry);
StreamUtils.Copy(fileStream, zipStream, new byte[4096]);
zipStream.CloseEntry();
zip.Add(zipEntry);

zip.CommitUpdate();
zip.Close();

但是它在 zip.Add(zipEntry) 上中断了;并抛出异常:

ZipException - Entry cannot have any data

我怎么也搞不明白哪里出了问题。

您正在使用的 ZipFile.Add 方法覆盖用于将目录、卷标等添加到 zip 文件:它 explicitly throws a ZipException 如果您传递 ZipEntry 包含数据。

根据 the documentation,如果您想将内存中的数据添加到 ZipFile,您需要使用 Add(IStaticDataSource dataSource, string entryName) 覆盖。您还需要创建 IStaticDataSource 的实现(下面的实现取自文档页面)。

所以你的代码应该是这样的:

void Main()
{
    string outputPath = @"C:\Scratch\test.zip";
    string myStringVariable = "<html><head><title>Title</title></head><body>Hello World</body></html>";

    var zip = ZipFile.Create(outputPath);
    zip.BeginUpdate();

    var fileStream = new MemoryStream(Encoding.Default.GetBytes(myStringVariable));

    var dataSource = new CustomStaticDataSource();
    dataSource.SetStream(fileStream);

    zip.Add(dataSource, "file.html");

    zip.CommitUpdate();
    zip.Close();
}

public class CustomStaticDataSource : IStaticDataSource {
    private Stream _stream;
    // Implement method from IStaticDataSource
    public Stream GetSource() {
        return _stream;
    }

    // Call this to provide the memorystream
    public void SetStream(Stream inputStream) {
        _stream = inputStream;
        _stream.Position = 0;
    }
}