Frage

I am tring to write generate a gzipped XML file from a MemoryStream. Here is what I have so far -

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

MemoryStream ms = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(ms, settings))
{
    // CREATE XML
}

Then I want to take that stream, and save it to a compressed file. I've seen many examples using GZipStream, but none exactly match this.

War es hilfreich?

Lösung

To save a document to a compressed file, you have to create two streams:

using (var fs = File.Create(fileName))
{
    using (var gz = new GZipStream(fs, CompressionMode.Compress))
    {
        doc.Save(gz);
    }
}

It assumes that you've created an XmlDocument. It then calls the XmlDocument.Save(Stream) method.

If you want to write XML directly to a compressed file, you can write:

using (var fs = File.Create(fileName))
{
    using (var gz = new GZipStream(fs, CompressionMode.Compress))
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        using (var writer = XmlWriter.Create(gz, settings))
        {
            // write xml here
        }
    }
}

That's the way that I'd suggest if you just want to write a gzip compressed XML file.

If you really want to go to a MemoryStream first, and then to a compressed file, you create the memory stream as you show in your question, and then you write it like this.

using (var fs = File.Create(fileName))
{
    using (var gz = new GZipStream(fs, CompressionMode.Compress))
    {
        ms.CopyTo(gz);
    }
}

Remember to set ms.Position = 0 before you do the copy.

Andere Tipps

First of all save this to a file

 XmlDocument doc = new XmlDocument();
 doc.Save(writer);

Then use the zip methods to compress it. For compressing

    byte[] b;
using (FileStream f = new FileStream("filename", FileMode.Open))
{
    b = new byte[f.Length];
    f.Read(b, 0, (int)f.Length);
}

using (FileStream f2 = new FileStream(fileName, FileMode.Create))
using (GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false))
{
    gz.Write(b, 0, b.Length);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top