Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

StreamReader Read Text File C#

Using StreamReader class in C#, users can read a text file. The example below uses an instance of StreamReader to read text from a file. A file "TestCases.txt" contains 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, create a class "StreamReaderUtility.cs" and write the following code. 

 

using System;
using System.IO;

namespace Com.Example.Csharp
{
    class StreamReaderUtility
    {
        public void ReadTextFile(String fileName)
        {
            try 
        {
            // Create an instance of StreamReader to read contents from a file. 
            // The using statement also closes the StreamReader
            using (StreamReader sr = new StreamReader(fileName)) 
            {
                string line;
                // Read and display lines from the file until the end of  
                // the file is reached. 
                while ((line = sr.ReadLine()) != null) 
                {
                    Console.WriteLine(line);
                }
            }
        }
        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 Program.cs class.

using System;

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

Run the Main method in the Program.cs file and see the result 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
[expected]=User should be redirected to login page after logging out. Login button should be displayed.

On the console, all the content of the TestCase.txt file is displayed.