SharpZipLib-将ZipEntry添加到ZipFile会引发ZipException [英] SharpZipLib - adding a ZipEntry to a ZipFile throws a ZipException
问题描述
我正在尝试使用内存字符串创建文件ZIP并保存.到目前为止,这是我的代码:
I'm trying to create ZIP with file from in-memory string and save it. Here is my code so far:
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)上中断了;并引发异常:
However it breaks on zip.Add(zipEntry); and throws exception:
ZipException -条目中不能包含任何数据
ZipException - Entry cannot have any data
我不知道怎么了.
推荐答案
您正在使用的ZipFile.Add
方法替代用于将目录,卷标等添加到zip文件:
The ZipFile.Add
method override you're using is for adding directories, volume labels, etc. to a zip file: it explicitly throws a ZipException
if you pass a ZipEntry
containing data.
如果您要将内存中的数据添加到,请按照文档进行操作. c3>,则需要使用Add(IStaticDataSource dataSource, string entryName)
替代.您还需要创建IStaticDataSource
的实现(以下内容摘自文档页面).
As per the documentation if you want to add in-memory data to a ZipFile
, you need to use the Add(IStaticDataSource dataSource, string entryName)
override. You'll also need to create an implementation of IStaticDataSource
(the one below is taken from the documentation page).
所以您的代码将类似于:
So your code would be something like:
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;
}
}
这篇关于SharpZipLib-将ZipEntry添加到ZipFile会引发ZipException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!