Different methods for reading text file in C#

following are the different methods which we can use to read text file in C#:

  1. Read complete file into a string
  2. Read complete file into a string with Streams Reader
  3. Read all the lines from a file into an array
  4. 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
            }
        }
    }
}

Author: Ankur

Have worked primarily in the domain of Calling, CRM and direct advertisers services. My technological forte is Microsoft Technologies especially Dot Net (Visual Studio 2003, 2005, 2008, 2010 and 2012) and Microsoft SQL Server 2000,2005 and 2008 R2. My Area of Expertise is in C#. Net, VB.Net, MS-SQL Server, ASP. Net, Silverlight, HTML, XML, Crystal Report, Active Reports, Infragistics, Component Art, ComponeOne, Lead Tools etc.