Saturday, January 28, 2017

CSharp - Read data from a text file

Read data from a text file.

Reading data from a text file in C# is pretty straight forward. The namespace that contains classes that you can use to perform input/output operations is "System.IO". To read data you can use the StreamReader class that provides many methods of reading data. Please refer to MSDN for details on the constructors of StreamReader.

In the example below, I am reading data from a text file called "data.txt". Since StreamReader class implements the IDisposable interface you can explicitly call the Dispose() method once you have finished reading the file or use can use the using{} construct which automatically disposes the StreamReader object.


Sample Code


using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
           static void Main(string[] args){
                ReadTextFile(); 
                Console.Read();
        }

        private static void ReadTextFile()
        {
            try
            {
                using (StreamReader streamReader = new StreamReader("C:\\data.txt"))
                {
                    string dataLine;
                    while ((dataLine = streamReader.ReadLine()) != null)
                    {
                        Console.WriteLine(dataLine);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: Unable to read the file");
                Console.WriteLine(ex.Message);
            }
        }
    }


1. using (StreamReader streamReader = new StreamReader("C:\\data.txt"))

The above line creates a new instance of StreamReader and puts a handle on the file located on C:\data.txt.


2. string dataLine;
    while ((dataLine = streamReader.ReadLine()) != null)
    {
            Console.WriteLine(dataLine);
    }

A variable dataLine is declared to hold each line read from the file. We  then call the ReadLine() method on the streamReader instance we created. 

The ReadLine()  method reads the whole line of characters and return the result as a string object. The result is stored in the dataLine variable. 

The value is then checked for null which checks if we have reached the end of the file. If this is not the case the value of the dataLine is output to the Console screen.

If a null is returned the loop condition fails and we don't attempt to read any further.

At the closing bracket of the using {....} construct the stream is disposed and the file to the handle is removed.

Note: Use the using {....} construct in you code to avoid memory leaks and fixing bugs later in the software life cycle.

Read the file in a single statement


If you don't want to read the file line by line, StreamReader provide another function to read data in a single go and return it as string. Use the ReadToEnd() method for such a scenario.

        private static void ReadTextFileAgain()
        {
            try
            {
                using (StreamReader streamReader = new StreamReader("d:\\data.txt"))
                {
                    string dataLine;
                    if ((dataLine = streamReader.ReadToEnd()) != null)
                    {
                        Console.WriteLine(dataLine);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: Unable to read the file");
                Console.WriteLine(ex.Message);
            }
        }



No comments:

Post a Comment