Skip to main content

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.

How to write to a Text File using C#

In this article we will see how to write text in txt file using C#.
In our dot-net application frequently we required to either read from text file or write to text file. We will see how to read from txt file later.
Here we will focus on writing into text file.

The main class file we are going to user for either reading or writing is “System.IO.File” class.

File class contains a various methods to write in a txt file.

To write all the text in a file see the below example

Example For WriteAllText

// WriteAllText method will creates a new file with given name in path,
// Writes the given string to a file,
// and then close the file.
// It is not required to eithe call Close() or Flush() method.

using System.IO;

class TextWriter
{
static void Main()
{
string filePath = @"C:\Users\Public\NewFile.txt"; // Check this path exists in your system or you can change it.
string textToWrite = "Here write those text or paragraph which you want to add into text file. You can write as many characters as you want.";

File.WriteAllText(filePath, textToWrite);
}
}

Now you can also write the list of lines into a text file. See below example for more detail and syntax.

Example For WriteAllLines

// WriteAllText method will creates a new file with given name in path,
// writes a collection of strings to the file,
// and then close the file.
// It is not required to eithe call Close() or Flush() method.

using System.IO;

class TextWriter
{
static void Main()
{
string filePath = @"C:\Users\Public\NewFile.txt"; // Check this path exists in your system or you can change it.
string[] linesToWrite = { "Text of first line to write into the notepad",
"Text of second line to write into the notepad",
"Text of third line to write into the notepad"
};

File.WriteAllLines(filePath, linesToWrite);
}
}

Above both example code are creating a new file or over right an existing file.

Now lets see how to append some text to an existing file. To append the text to existing file here we will use StreamWriter class from System.IO namespace.

Example For WriteLine

// Here we will use using statement, which will call flushes and closes the stream. It will also calls the dispose on the stream object itself.

using System.IO;

class TextWriter
{
static void Main()
{
string filePath = @"C:\Users\Public\NewFile.txt"; // Check this path exists in your system or you can change it.
using (StreamWriter fileToAppend = new StreamWriter(filePath, true))
{
fileToAppend.WriteLine("Text of fourth line to write into the notepad");
}
}
}

Notes:
In below cases you may get an exceptions
– File is exists at given path but read only.
– If disk is full
– If path name is too long etc

You can download an example here

Understand the value type and reference type

In previous article we have seen difference between primary key and unique key. Today we will see the difference between value type and reference type.

Let first see what are the value types and what are the reference types.

What are Value Types?
Variables which stores direct data are called value types they are stored on a stack. They contains the actual value rather then reference.
For an example enum, structure int are value types.

What are Reference Types?
Variables which stores reference of actual data are called Reference types. They are stored on heap but contain the address on heap.
For an example Array, class, object, string, delegate, interface are reference type.

Now lets see the difference between both of them.

Before that let me show you the difference between Stack and Heap

Difference between Stack and Heap

Stack Heap
Stack is used for value types. Heap is used for reference types
Values are stored one on another like a stack Values are stored in random order.like dumped into a big space

Difference between value type and reference types

Value Type Reference Type
Value Type are stored on stack Reference Type are stored on heap
It contains actual value It contains reference of a value
For value type memory is allocated at compile time For reference type memory is allocated at run time
Once they go out of scope it will automatically removed from stack, so no need for garbage collector. In reference type it required garbage collector to free the memory.
If value type is null able then only it contains null value, otherwise not Reference Type can contain null values.

That’s it.