Create and read xml file using GZipStream - CSharp File IO

CSharp examples for File IO:GZip

Description

Create and read xml file using GZipStream

Demo Code

using System;//from ww w .j  a  v a 2 s .c  om
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using static System.Console;
using System.IO;
using System.Xml;
using System.IO.Compression;
class Program
{
   static void Main(string[] args)
   {
      string gzipFilePath = "streams.gzip";
      FileStream gzipFile = File.Create(gzipFilePath);
      using (GZipStream compressor = new GZipStream(gzipFile, CompressionMode.Compress))
      {
         using (XmlWriter xmlGzip = XmlWriter.Create(compressor))
         {
            xmlGzip.WriteStartDocument();
            xmlGzip.WriteStartElement("callsigns");
            xmlGzip.WriteElementString("callsign", "asdfasdfa");
         }
      }
      WriteLine($"{gzipFilePath} contains {new FileInfo(gzipFilePath).Length} bytes.");
      WriteLine(File.ReadAllText(gzipFilePath));
      WriteLine("Reading the compressed XML file:");
      gzipFile = File.Open(gzipFilePath, FileMode.Open);
      using (GZipStream decompressor = new GZipStream(gzipFile, CompressionMode.Decompress))
      {
         using (XmlReader reader = XmlReader.Create(decompressor))
         {
            while (reader.Read())
            {
               if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "callsign"))
               {
                  reader.Read(); // move to the Text node inside the element
                  WriteLine($"{reader.Value}"); // read its value
               }
            }
         }
      }
   }
}

Result


Related Tutorials