0
0
C Sharp (C#)programming~5 mins

Reading text files in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Reading text files lets your program get information stored in files. This helps your program use data saved earlier or from other sources.

You want to load a list of names saved in a file to show in your app.
You need to read a configuration file to set up your program.
You want to process a log file to find errors or important events.
You have a text file with data and want to analyze or display it.
Syntax
C Sharp (C#)
string[] lines = System.IO.File.ReadAllLines("filename.txt");

// or to read all text as one string
string text = System.IO.File.ReadAllText("filename.txt");

ReadAllLines reads the file and returns each line as an array element.

ReadAllText reads the whole file as one big string.

Examples
This reads all lines from data.txt and prints each line.
C Sharp (C#)
string[] lines = System.IO.File.ReadAllLines("data.txt");
foreach (string line in lines)
{
    Console.WriteLine(line);
}
This reads the entire content of message.txt as one string and prints it.
C Sharp (C#)
string text = System.IO.File.ReadAllText("message.txt");
Console.WriteLine(text);
Sample Program

This program reads all lines from a file named example.txt and prints each line to the console.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        // Assume file 'example.txt' exists with some text
        string[] lines = System.IO.File.ReadAllLines("example.txt");
        Console.WriteLine("Contents of example.txt:");
        foreach (string line in lines)
        {
            Console.WriteLine(line);
        }
    }
}
OutputSuccess
Important Notes

Make sure the file path is correct or you will get an error.

If the file is large, reading all lines at once might use a lot of memory.

You can also read files line by line using streams for better memory use.

Summary

Use File.ReadAllLines to get all lines as an array.

Use File.ReadAllText to get the whole file as one string.

Always check the file path and handle errors in real programs.