Users Online

· Guests Online: 104

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

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

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

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.01 seconds
10,853,545 unique visits