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.