Home » Asp.Net » How to Read from a Text File using C#

How to Read from a Text File using C#

In previous article we have see “How to write to a Text File using C#“, Now in this article we are going to learn how can we read text file using C#. In most of the application either we are writing something to text file or reading from text file. Reading from and writing to text file is essential for major application. So lets see the code for reading text file using C#.

The main important class is File for Read from text file which exists in System.IO namespace.
So first we need to import System.IO namespace to our project.

Now lets see example for ReadAllText method

ReadAllText

ReadAllText method will read all the content of a given file. It will take 1 parameter as a full file path.

Example #1

using System;
using System.IO;

namespace ReadFromTextFile
{
class Program
{
static void Main(string[] args)
{
string pathToReadFile = @"C:\Users\Public\";

// Example #1
// Read the file as one string.
string textFromFile = File.ReadAllText(pathToReadFile +"File1.txt");
Console.WriteLine(textFromFile);
Console.ReadKey();

}
}
}

ReadAllLines

ReadAllLines method will read all the lines of a given file in an array. It will also take 1 parameter as a full file path.

Example #2

using System;
using System.IO;

namespace ReadFromTextFile
{
class Program
{
static void Main(string[] args)
{
string pathToReadFile = @"C:\Users\Public\";

// Example #1
// Read the file as one string.
string textFromFile = File.ReadAllText(pathToReadFile +"File1.txt");
Console.WriteLine(textFromFile);

string[] linesOfText = File.ReadAllLines(pathToReadFile + "File2.txt");

foreach (string singleLine in linesOfText)
{
// print each line on a different line.
Console.WriteLine("\n" + singleLine);
}

//Lets system wait until user press any key to see the result on a console window
Console.ReadKey();
}
}
}

Please change path of “pathToReadFile” variable if that path does not exists on your system, also change the name of txt file.
If file path doesn’t exist on your system then it may cause an exception

You can download an example here.

About

Site Admin is a writer of http://www.codingsharp.com website. He is a software professional with hands on 4+ years of experience. Generally he writes an article about Javascript, SQL Server and JQuery. Here he shares his notes, experiences, examples.

About Coding Sharp

Coding sharp is a blog where you can find the authors personal experience, tutorials, examples, code samples, resources related to C#, Asp.Net, Linq, Ajax, MVC, Entity Framework, SQL Server, jQuery, Visual Studio.

Pages