C# read text file

In this post we are going to discuss how to read text file in c#. .Net provides File class in System.IO namespace which contains methods to read file from the disk.
We can read all the contents of text file in one go using ReadAllText() method of File class.
Also we can use ReadAllLines() method of File class and read each line of the file and store it in the string array and then by iterating through string array we can show each line.
System.IO namespace also contains StreamReader class which has ReadLine() method that we can use to read a Text file one line at a time.We will now see code samples to read file in C# by all the ways we discussed above.


Sample code to read text file in one go [C#]


We will use here ReadAllText() method in File class read all the contents of text file as one string [C#]

class ReadFile
{
 static void Main()
 {
   // Example to Read the file as a whole string.
    string fileText =  System.IO.File.ReadAllText( @"C:\MyFolder\TextFile.txt"); 
   // Show read content of text file in text box .
    TextBox1.Text = fileText ;
}
}

Sample code to read text file in line by line in string array [C#]

we will use here to read all lines by line in text file using ReadAlllines() method in File class.


class ReadFileLines
{
 static void Main()
{ 
   // Example to Read the file lines into a string array.
   string[] allLines = System.IO.File.ReadAllLines (@"C:\MyFolder\TextFile.txt"); 
   //Write text file contents to text box
  foreach(string line in allLines)
  {
   TextBox.Text += "\t\n" + line;
  }
 }
}

we will now look how we can use ReadLine() method of StreamReader class to read each line of text file.


Sample code to read each line of text file [C#]


int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(@"c:\test.txt");
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine (line);
counter++;
}
file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
System.Console.ReadLine();

delete folder, directory c#

In order to remove a directory or folder using C#, .Net framework provides System.IO namspace which provides Directory.Delete method.
Directory.Delete
is a static method that gives you easy way to delete or remove folder or directory. Also we can delete directory or folder using DirectoryInfo class of System.IO namespace.

Examples of deleting directory or folder Directory.CreateDirectory:

Following is sample code for deleting or removing directory or folder on root i.e. at C:/ drive

using System.IO;

class DeleteFolder
{
static void Main()
{

// Delete Directory/folder on C:\ Drive.
Directory.Delete("C:\\TestDirectory");
}
}


Sample code to delete directory using System.IO DirectoryInfo class

using System.IO;

class CreateNewFolder
{
static void Main()
{

// Get Directory info or folder info.
DirectoryInfo dir = new DirectoryInfo(@"c:\TestDirectory");
dir.Delete();
}
}