Showing posts with label FileStream. Show all posts
Showing posts with label FileStream. Show all posts

C# : How to read a text file


This is a very basic example where we explain how can we read text files from C#.
We will show three examples:

Example 1:
We will read all the text from a file and store it in a string variable.

For this we will be using C# inbuilt utility function: System.IO.File.ReadAllText

Method signature:
public static string ReadAllText(string path);


Example 2:
We will read all the text from a file line by line and then store each line as an element in a string array.
For this we will be using C# inbuilt utility function: System.IO.File.ReadAllLines

Method signature:
public static string[] ReadAllLines(string path);

We have developed a console application to showcase the feature.The source code for reading file is displayed below:

class Program
    {
        static void Main()
        {
           

            // Read the file as one string.
            string text = System.IO.File.ReadAllText(@"C:\Example1.txt");

            // Display the file contents to the console. Variable text is a string.
            System.Console.WriteLine("*****************EXAMPLE 1*********************");
            System.Console.WriteLine("Contents of Example1.txt = {0} \n \n", text);