我尝试执行以下操作:
var mem = new MemoryStream();
var xmlWriter = new XmlTextWriter(mem, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
var xmlSerializer = new XmlSerializer(typeof(Project));
xmlSerializer.Serialize(xmlWriter, this);
xmlWriter.Flush();
mem.Seek(0, SeekOrigin.Begin);
using (var zip = new ZipFile())
{
ZipEntry e = zip.AddEntry("file.xml", mem);
e.Comment = "XML file";
zip.AddFile("file.xml");
zip.Save(filename);
}
mem.Close();
但是在调用zip.Save时抛出异常。
我在这里做错了什么?
基本思想是将类Project序列化为内存流中的XmlFile。然后在DotNetZip中使用memorystream并将其压缩到文件。
答案 0 :(得分:1)
你收到了什么例外?这段代码对我有用:
using (ZipFile zip = new ZipFile())
using (MemoryStream memStream = new MemoryStream())
using(XmlTextWriter xmlWriter = new XmlTextWriter(memStream, System.Text.Encoding.UTF8))
{
xmlWriter.Formatting = Formatting.Indented;
var xmlSerializer = new XmlSerializer(typeof (Project));
xmlSerializer.Serialize(xmlWriter, new Project());
xmlWriter.Flush();
memStream.Seek(0, SeekOrigin.Begin);
zip.AddEntry("xmlEntry.xml", memStream);
var myDir = @"C:\myfolder\";
Directory.CreateDirectory(myDir);
zip.Save(Path.Combine(myDir, "myfile.zip"));
}