我正在尝试使用内存字符串从文件创建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-条目不能包含任何数据
我以某种方式无法弄清楚出了什么问题。
最佳答案
您正在使用的ZipFile.Add
方法替代用于将目录,卷标等添加到zip文件:如果传递包含数据的ZipException
,则它为explicitly throws a 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;
}
}