Christian Sauer
Christian Sauer

Reputation: 10969

Serializing to XML and compressing the result - how to add a XML filetype?

I am using the following method to serialize objects:

    /// <summary>
    /// Serializes a file to a compressed XML file. If an error occurs, the exception is NOT caught.
    /// </summary>
    /// <typeparam name="T">The Type</typeparam>
    /// <param name="obj">The object.</param>
    /// <param name="fileName">Name of the file.</param>
    public static void SerializeToXML<T>(T obj, string fileName)
    {
        var serializer = new XmlSerializer(typeof(T));

        using (var fs = new FileStream(fileName, FileMode.Create))
        {
            using (var compressor = new GZipStream(fs, CompressionMode.Compress))
            {
                serializer.Serialize(compressor, obj);
            }
        }
    }

Thats works without a hitch, but there is a minor problem: The method creates a .zip file which contains the compressed xml which has no file Extension at all. How can I modify this method, so that the correct file extension is added to the compressed file?

Example: Suppose I have the following code:

public class test
{
   public string test {get; set;}
}

public void save()
{
  var newTest = new test();
  newTest.test = "bla";
  SerializeToXML(newTest, c:\test.zip")
}

Upvotes: 1

Views: 199

Answers (2)

Jevgenij Nekrasov
Jevgenij Nekrasov

Reputation: 2760

You can try to rename file 'test.zip' to 'test.xml.zip' then after decompression zip extension will be removed and you will have only xml.

Upvotes: 3

Luaan
Luaan

Reputation: 63772

GZipStream only creates a compressed stream. It doesn't create a full zip file, and you can't use it to create a file/directory structure inside that zip file.

Try SharpZipLib if you need that - icsharpcode.net/opensource/sharpziplib

If you don't, just continue using GZipStream, but note that the resulting file is a gzip file, not zip. The somewhat standardised notation for gzips is basically to include the filename of the uncompressed file in the filename of the compressed file (what Jevgenij said), eg. test.xml.gz. This should yield the "correct" file name when you unzip the file using 7zip, gunzip or other tools that handle this "properly".

Upvotes: 2

Related Questions