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);

            System.Console.WriteLine("*****************EXAMPLE 2*********************");
          
            // Read each line of the file into a string array. Each element
            // of the array is one line of the file.
            string[] lines = System.IO.File.ReadAllLines(@"C:\Example2.txt");

            // Display the file contents by using a foreach loop.
            System.Console.WriteLine("Contents of Example2.txt = ");
            foreach (string line in lines)
            {
                // Use a tab to indent each line of the file.
                Console.WriteLine("\t" + line);
            }

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }

Example 3:
By Using object of FileStream class and read the file in the form of byte array

class Program
    {
        static void Main(string[] args)
        {
            //Creating the object of FileStream Class and opening the file in Read mode
            FileStream fs = new FileStream(@"C:\Example1.txt"FileMode.Open, FileAccess.Read);
            //Declaring the byte array in which we will read the file
            byte[] bt = new byte[fs.Length];
            //reading the file
            fs.Read(bt,0,bt.Length);
            //Printing the file by converting the byte array in to the string
            Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(bt));
            Console.ReadLine();
           
        }
       
    }


Here is the Screenshot of Output:


No comments:

Post a Comment