• Startseite
  • Tutorials
  • Kontakt
  • Mein Account
Panjutorials
  • Startseite
  • Tutorials
  • Kontakt
  • Mein Account

Read Data from File in CSharp

In this article you learn how to read data from a file in CSharp. There are two different ways. Both are explained in the code and can be adopted.

The underlying file is fairly simple and has the following content.

This is a line
The next line

The content is stored in the file Text.txt and is read with the following approach.

Example of reading data from a file in CSharp

class Programm
    {


        public static void Main(string[] args)
        {
            // The file used here is a simple one
            // Text file with a little text.

            // Example 1
            // Read the complete file as a string
            string text = System.IO.File.ReadAllText(@"D:\Tutorials\CSharp\text.txt");

            // Showing the text
            System.Console.WriteLine("Content of text.txt = {0}", text);

            // Example #2
            // Read the text in each line and store it in an array
            // each entry of the array is a line
            string[] lines = System.IO.File.ReadAllLines(@"D:\Tutorials\CSharp\text.txt");

            // Show the content via foreach loop
            System.Console.WriteLine("Content of text.txt = ");
            foreach (string line in lines)
            {
                // Using a tab to make the content more readable
                Console.WriteLine("\t" + line);
            }

            Console.WriteLine("Press enter to close the application.");
            System.Console.ReadLine();
        }


    }

So you see, it really is not a witchcraft to read from files. The only important thing is that you use a file type that can be read.

You can use regular expressions to filter and edit text. We will deal with it in the next article.