Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

TextReader Read Text File C#

Using TextReader class, we can read contents of a text file. The TextReader class is an abstract class, so you do not instantiate in your code. The StreamReader class derives from TextReader and provides implementations of the member for reading from a Stream. In this example, we read a TestCase.txt file. The file has the following content. 

 

 

[id]=00001
[module]=Login
[expected]=Users should be able to login with valid user name and password. Logout link should be displayed. 

[id]=00002
[module]=Logout
[expected]=User should be redirected to login page after logging out. Login button should be displayed. 

In your C# project, write the following code in the "TextReaderUtility.cs" class file.

using System;
using System.IO;
using System.Text;

namespace Com.Example.Csharp
{
    class TextReaderUtility
    {
        public void ReadTextFile(String fileName)
        {
           StringBuilder builder=new StringBuilder();
            try
            {

                using (StreamReader reader = File.OpenText(fileName))
                {
                    string line;
                    // Read and display lines from the file until the end of  
                    // the file is reached. 
                    while ((line = reader.ReadLine()) != null)
                    {
                        //Append each line to the String Builder
                        builder.Append(line);
                    }

                    Console.WriteLine(builder.ToString());
                }
            }
            catch (Exception e)
            {
                // Display information about what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
        }
    }
}

Write the following code in the main method of the Program.cs class.

using System;

namespace Com.Example.Csharp
{
    class Program
    {
        private static void Main(string[] args)
        {
            //Read Text File with Stream Reader
            TextReaderUtility textReaderUtility=new TextReaderUtility();
            textReaderUtility.ReadTextFile("TestCases.txt");
            Console.ReadKey();
        }
    }
}

Run the Main method in the Program.cs file and see the result below. The result is displayed on the console.

[id]=00001[module]=Login[expected]=Users should be able to login with valid user
 name and password. Logout link should be displayed. [id]=00002[module]=Logout[e
xpected]=User should be redirected to login page after logging out. Login button
 should be displayed.

The console displayed the content of the TestCase.txt file. From the console output, you see that the file content format is not maintained when using TextReader and StringBuilder to read a text file.