Skip to main content

Writing XML with the XmlWriter class

In previous article we have see about writing and reading text document, but now it’s time to start dealing with XML file. Anyhow XML is just a plain text, we can simply start writing an XML tags to the file and save it with .xml file extension. But for .net framework it is very easy and safe to handle.

For writing an XML file .net framework provides two different options.
XMLWriter and XmlDocument, we will see XMLDocument in the next article. In this article we will focus on XMLWriter approach

Let’s see the basic different between XmlWriter and XmlDocument. XMLWriter uses less memory compare to XmlDocument, that is the only 1 issue if we are writing a vey big file. Another difference is if we are modofing an xml file using XmlDocument, we can read an exisitng file, change it as required and update the file while in XMLWriter we need to create the whole document from scratch every time. That’s it, so it is upto user’s preference and situation when which one should be used.

Now lets have a look at the exmple of writing XML file using XmlWriter class.

using System.Xml;

namespace XmlWriterExample
{
    class Developer
    {
        public int Id { get; set; }
        public string FullName { get; set;  }
        public string Department { get; set; }
        public int Salary { get; set; }
    }

    class Program
    {
        static void Main()
        {
            Developer[] developers = new Developer[2];
            developers[0] = new Developer() {Id= 2, FullName="Tarun Dudhatra", Department = ".Net", Salary=50000 };
            developers[1] = new Developer() { Id = 6, FullName = "Milan Dudhatra", Department = ".Net", Salary = 40000 };

            using (XmlWriter fileWriter = XmlWriter.Create(@"D:\Tarun\developer.xml"))
            {
                fileWriter.WriteStartDocument();
                fileWriter.WriteStartElement("developers");

                foreach (Developer developer in developers)
                {
                    fileWriter.WriteStartElement("Developer");

                    fileWriter.WriteElementString("ID", developer.Id.ToString());
                    fileWriter.WriteElementString("FullName", developer.FullName);
                    fileWriter.WriteElementString("Department", developer.Department);
                    fileWriter.WriteElementString("Salary", developer.Salary.ToString());

                    fileWriter.WriteEndElement();
                }

                fileWriter.WriteEndElement();
                fileWriter.WriteEndDocument();
            }
        }
    }
}

The above C sharp code will generate the following XML file:

<?xml version="1.0" encoding="utf-8"?>
<developers>

	<Developer>
		<ID>2</ID>
		<FullName>Tarun Dudhatra</FullName>
		<Department>.Net</Department>
		<Salary>50000</Salary>
	</Developer>
	
	<Developer>
		<ID>6</ID>
		<FullName>Milan Dudhatra</FullName>
		<Department>.Net</Department>
		<Salary>40000</Salary>
	</Developer>
	
</developers>

Here first we have created an instace of the XmlWriter class with one parameter (obviously it a path of xml file, where we want to create a xml file).

We have started xml document with WriteStartDocument() method, and then create an element called “developers” this will be converted to in xml file. After that we have created an another element called “Developer” which will be child element of previously created “developers” element. Now we have created 4 child element called Id, Fullname, Department and Salary using WriteElementString() method. We then close the WriteEndElement() method for Developer node and out side the forloop we call that method again for “developers” node. After writing all the element to root element we will end the document by calling WriteEndDocument() method.

That’s simple it takes to generate an xml file using XmlWriter class. In the next blog post we will see how to write an xml file using XmlDocument class.

 

Download the sample project

StreamReader

StreamReader class

In my previous article we have have seen how to read from text file using File class and how to write into text file using StreamWriter class. In this article we will see how to read from text file using StreamReader  class.

Using Statements: It is recommended to use using statements while we are using StreamReader class, which ensures that is is removed from the memory once it is no longer needed. The syntax is very easy to use.
StreamReader class reads text file, it is available in System.IO namespace. It provides very good performance. Using StreamReader we can read a file synchronously and asynchronously, we need to provide a relative or absolute path to the file.

Lets check with the example that how to synchronously read a line from text file using StreamReader class. First we need to declare and initialize an instance of StreamReader class with using statement.
Example 1

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string line;
        using (StreamReader reader = new StreamReader(@"C:\Users\Tarun\Documents\File1.txt"))
        {
            line = reader.ReadLine();
        }
        Console.WriteLine(line);
        Console.Read();
    }
}

Example 2
Now lets check with the example that how to read all the line from a text file using StreamReader class.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        using (StreamReader reader = new StreamReader(@"C:\Users\Tarun\Documents\File1.txt"))
        {
            while (true)
            {
                string line = reader.ReadLine();
                if (line == null)
                {
                    break;
                }
                Console.WriteLine(line); // Use line.
            }
            Console.Read();
        }
    }
}

In the above example we have used a while loop to read all the line 1 by 1. If we don’t want to use while loop to read whole file then we can also use reader.ReadToEnd() method which will read the content of a text file to the end.

Scope : Scope is a code block between curly braces. Scope allows compiler to make some assumption about the program when some code is unreachable. So garbage collector can reclaimed the program’s memory.

See the below output for example 2

streamreader
streamreader

We have see the synchronous read operation in above both example, now let’s see asynchronous read operation.
asynchronous we need to make async method and have to use await keyword before calling a method.

see the example below.

private async void ReadFileButton_Click(object sender, EventArgs e)
{
    string textFileOutPut = string.Empty;
    try
    {
        using (StreamReader reader = new StreamReader(@"C:\Users\Tarun\Documents\File1.txt"))
        {
            String line = await reader.ReadToEndAsync();
            textFileOutPut = line;
        }
    }
    catch (Exception ex)
    {
        textFileOutPut = "Could not read the file, " + ex.Message;
    }
}

We have created a winform application and put a button called ReadFileButton, and on click event (which we made async) ReadToEndAsync() with await keyword so it will read the given file asynchronously.

Note : With the using statement and StreamReader class we have read a text file. It is a excellent class and useful for many C# programmers.
Download the whole working code here.

 

Understanding StreamWriter class

We have seen how to write in text file using File class in our previous article. Today we will see how to use StreamWriter class to write in a text file.
This class is very helpful to write text data into files. This class contains method to write to a file synchronously like Write and WriteLine or asynchronously WriteAsync and WriteLineAsync.
Using Statements. It is recommended to use using statements while we are using Stream Writer class, which ensures that is is removed from the memory once it is no longer needed. The syntax is very easy to use.
Lets check with the example that how to synchronously write to a text file using Stream Writer class. First we need to declare and initialize an instance of the class with using statement. It is available is available in System.IO namespace

Example 1

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamWriter writer = new StreamWriter(@"C:\Users\Tarun\Documents\File1.txt"))
        {
            writer.Write("First Word");
            writer.WriteLine("Second Word");
            writer.WriteLine("Third Line to write into the text file.");
            writer.Close();
            Console.ReadLine();
        }
    }
}

Example 2
Now lets check with the example that how to asynchronously write to a text file.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamWriter writerAsync = new StreamWriter(@"C:\Users\Tarun\Documents\AsyncFile1.txt"))
        {
            writerAsync.WriteAsync("First Word");
            writerAsync.WriteLineAsync("Second Word");
            writerAsync.WriteLineAsync("Third Line to write into the text file.");
            writerAsync.Close();
            Console.ReadLine();
        }

    }
}

See the below output for both example

StreamWriter class output
StreamWriter class output

Note : With the using statement and Stream Writer class we have written a text file. It is a excellent class and useful for many C# programmers.
Download the whole working code here.