C# Program to Read Lines from a File until the End of File is Reached
Posted by Superadmin on August 13 2022 10:04:11

C# Program to Read Lines from a File until the End of File is Reached

 

This is a C# Program to read lines from a file until the end of file is reached.

Problem Description

This C# Program Reads Lines from a File until the End of File is Reached.

Problem Solution

Here StreamWriter writes text files and this program read lines from a file that is created.

Program/Source Code

Here is source code of the C# Program to Read Lines from a File until the End of File is Reached. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Read Lines from a File until the End of File is Reached
 */
using System;
using System.IO;
class Test
{
    public static void Main()
    {
        string path = @"c:\sri\srip.txt";
        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            using (StreamWriter sw = new StreamWriter(path))
            {
                sw.WriteLine("This");
                sw.WriteLine("text is");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }
 
            using (StreamReader sr = new StreamReader(path))
            {
                while (sr.Peek() >= 0)
                {
                    Console.WriteLine(sr.ReadLine());
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
        Console.Read();
    }
}
Program Explanation

This C# program is used to read lines from a file until the end of file is reached. We have defined the path of the file using ‘path’ variable. Using if condition statement check the path exists or not.

 

If the path exists then execute if condition statement and delete the path of the file. The StreamWriter writes text files and this program read lines from a file that is created. Print the read and end lines of a file.

Runtime Test Cases
 
This 
text is
to test
reading