This is a C# Program to read the contents of the file.
This C# Program Reads 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.
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(); } }
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.
The text which your are reading are read from the file named myfile.txt that is created already.
Sanfoundry Global Education & Learning Series – 1000 C# Programs.
- Practice Computer Science MCQs
- Check Computer Science Books
- Apply for Computer Science Internship
- Practice MCA MCQs
- Check MCA Books