Create xml file and write xml data to it - CSharp File IO

CSharp examples for File IO:Text File

Description

Create xml file and write xml data to it

Demo Code

using System;/*from  w  w  w  .  j  ava2s.  c om*/
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using static System.Console;
using System.IO;
using System.Xml;
class Program
{
   static void Main(string[] args)
   {
      FileStream xmlFileStream = null;
      XmlWriter xml = null;
      try
      {
         string xmlFile = "streams.xml";
         xmlFileStream = File.Create(xmlFile);
         xml = XmlWriter.Create(xmlFileStream, new XmlWriterSettings { Indent = true });
         xml.WriteStartDocument();
         xml.WriteStartElement("A");
         xml.WriteElementString("A", "item");
         xml.WriteEndElement();
         xml.Close();
         xmlFileStream.Close();
         WriteLine($"{xmlFile} contains {new FileInfo(xmlFile).Length} bytes.");
         WriteLine(File.ReadAllText(xmlFile));
      }
      catch (Exception ex)
      {
         WriteLine($"{ex.GetType()} says {ex.Message}");
      }
      finally
      {
         if (xml != null)
         {
            xml.Dispose();
            WriteLine("The XML writer's unmanaged resources have been disposed.");
         }
         if (xmlFileStream != null)
         {
            xmlFileStream.Dispose();
            WriteLine("The file stream's unmanaged resources have been disposed.");
         }
      }
   }
}

Result


Related Tutorials