1

我尝试执行以下操作:

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 中的内存流并将其压缩到文件中。

4

1 回答 1

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"));
        }
于 2014-01-22T16:58:25.087 回答