Skip to content
September 25, 2008 / kiranpatils

Convert XDocument to GZip format

Here is the method which will help you..

/// <summary>
/// This function will be used to Compress XML DATA
/// using Gzip Stream
/// </summary>
/// <param name=”xDocument”>XMLDocument to compress</param>
/// <returns>byte array</returns>
private byte[] ConvertXDocumentToGzip(XDocument xDocument)
{
//buffer to write Compressed data
byte[] buffer;

//Compress the XML DATA
MemoryStream memoryStream = new MemoryStream();
XmlWriter xmlWriter = XmlWriter.Create(memoryStream);

//Save data to memoryStream
xDocument.Save(xmlWriter);

//writer Close
xmlWriter.Close();

//Reset Memorystream postion to 0
memoryStream.Position = 0;

//create buffer of total content Length
buffer = new byte[memoryStream.Length];

//Create a stream to compress the data
GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress);
//compress the data
gzipStream.Write(buffer, 0, buffer.Length);

//Close the underlying streams
gzipStream.Flush();
gzipStream.Close();

memoryStream.Flush();
memoryStream.Close();

//return compressed data as byte array
return buffer;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: