Users Online

· Guests Online: 10

· 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 a Text File

C# Program to Read a Text File

 

This is a C# Program to read the contents of the file.

Problem Description

This C# Program Reads the Contents of a File.

Problem Solution

It uses the library functions to read the data from the file that is created already in the same path of the program that is written.

Program/Source Code

Here is source code to Read the Contents of a File.The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.



/*
 * C# Program to Read Contents of a File
 */
using System;
using System.IO;
class FileRead
{
    public void readdata()
    {
        FileStream fs = new FileStream("Myfile.txt", FileMode.Open, FileAccess.Read);
        //Position the File Pointer at the Beginning of the File
        StreamReader sr = new StreamReader(fs);
        //Read till the End of the File is Encountered
        sr.BaseStream.Seek(0, SeekOrigin.Begin);
        string str = sr.ReadLine();
        while (str != null)
        {
            Console.WriteLine("{0}", str);
            str = sr.ReadLine();
        }
        //Close the Writer and File
        sr.Close();
        fs.Close();
    }
    public static void Main(String[] args)
    {
        FileRead fr = new FileRead();
        fr.readdata();
    }
}
Program Explanation

This C# program is used to read the contents of a file. It uses the library functions to read the data from the file that is created already in the same path of the program that is written. The ‘StreamReader’ is used to position the file pointer at the beginning of the file.

 

 

Then BaseStream.Seek() function is used to read till the end of the file is encountered. Using while loop check the condition that the value of ‘str’ variable is not equal to null. If the condition is true, then execute the iteration of the loop. Using ReadLine() function we are reading the content in the file and we are close the writer and file.

Runtime Test Cases
 
The text which your are reading are read from the file 
named myfile.txt that is created already.

 

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.35 seconds
15,067,481 unique visits