SoFunction
Updated on 2025-03-06

A small example of using C# to read text file content in Windows system

Read content in a text file

This example reads the contents of a text file to use the static methods of the option class ReadAllText and ReadAllLines.

class ReadFromFile
{
  static void Main()
  {
    // The files used in this example are created in the topic
    // How to: Write to a Text File. You can change the path and
    // file name to substitute text files of your own.

    // Example #1
    // Read the file as one string.
    string text = (@"C:\Users\Public\TestFolder\");

    // Display the file contents to the console. Variable text is a string.
    ("Contents of  = {0}", text);

    // 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 = (@"C:\Users\Public\TestFolder\");

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

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

Read text files one line at a time
This example uses the ReadLine method of the StreamReader class to read the contents of a text file (one line at a time) into a string. All text lines are saved in the string line and displayed on the screen.

int counter = 0;
string line;

// Read the file and display it line by line.
 file = 
  new (@"c:\");
while((line = ()) != null)
{
   (line);
  counter++;
}

();
("There were {0} lines.", counter);
// Suspend the screen.
();