following are the different methods which we can use to read text file in C#:
- Read complete file into a string
- Read complete file into a string with Streams Reader
- Read all the lines from a file into an array
- Read a file line by line into string
Read complete file into a string
To read complete file into a single string we use ReadAllText method of System.IO.File class
private void GetContentInString() { string srtCompleteFileText = System.IO.File.ReadAllText(@"C:\test1.txt"); }
Read complete file into a string with Streams Reader
To read a file with Stream Reader we will use System.IO.StreamReader class.
public static string getFileAsString(string Full_fileName) { StreamReader strReader = null; string strcontents = null; try { FileStream flStream = new FileStream(Full_fileName, FileMode.Open, FileAccess.Read); strReader = new StreamReader(flStream); strcontents = strReader.ReadToEnd(); } finally { if (strReader != null) { strReader.Close(); } } return strcontents; }
Read all the lines from a file into an array
We use ReadAllLines function of System.IO.File class to read all line of a file into single line array
private void GetContentInArray() { string[] All_lines = System.IO.File.ReadAllLines(@"C:\test12.txt"); }
Read a file line by line into string
We use ReadLine function of System.IO.File class to read a file line by line.
using System; using System.IO; namespace ReadString { class ReadAllLine { public static void Main(string[] args) { StreamReader sReader = new StreamReader("C:\text.txt"); string my_line; while ((my_line = sReader.ReadLine()) != null) { Console.WriteLine("My_Line:" + my_line); } if (sReader != null) { sReader.Close(); //should be in a "finally" or "using" block } } } }