如何序列化xml文件并在内存中压缩它们

时间:2017-05-23 08:42:29

标签: c# asp.net-mvc c#-4.0 serialization

我编写了一个代码,用于序列化三个XML文档并将它们写入本地文件夹。我想知道是否可以序列化它们并保存在内存中而不是使用本地路径?此外,是否可以“动态”压缩这些文件,以便我可以将压缩文件附加到电子邮件中?这是我到目前为止的代码,有人能给我一个如何修改这段代码的线索,以便它在内存中完成所有操作吗?

 XmlSerializer serializer = new XmlSerializer(typeof(DataCollectionXMLModel.ArrayOfCertQuestion));

 for (int i = 0; i < cachedList.Count; i++)
   {
       if (i == 0) documentName = "commonInformation.xml";
       if (i == 1) documentName = "contactInformation.xml";
       if (i == 2) documentName = "extraInformation.xml";

       StreamWriter writer = new StreamWriter("C:\\Temp\\" + documentName);
       this.serializer.Serialize(writer, cachedList[i]);
       writer.Close();
    }

1 个答案:

答案 0 :(得分:0)

您可以使用内存流来编写序列化数据并创建存档。

示例:

public class Program
{
    [Serializable]
    public class Tst
    {
        public string A { get; set; }
    }

    static void Main(string[] args)
    {
        var serializer = new XmlSerializer(typeof(Tst));

        var arr = new Tst[]
        {
            new Tst { A = "s1"},
            new Tst { A = "s2"},
        };

        using (var stream = new MemoryStream())
        {
            using (var archive = new System.IO.Compression.ZipArchive(stream, ZipArchiveMode.Create, true))
            {
                for (int i = 0; i < arr.Length; i++)
                {
                    var documentName = "def.xml";

                    if (i == 0) documentName = "commonInformation.xml";
                    if (i == 1) documentName = "contactInformation.xml";

                    var entry = archive.CreateEntry(documentName, CompressionLevel.NoCompression);

                    using (var writer = new StreamWriter(entry.Open()))
                    {
                        serializer.Serialize(writer, arr[i]);
                    }

                }
            }
        }


    }
}