0
0
CsharpHow-ToBeginner · 3 min read

How to Use File.ReadAllText in C# to Read File Content

Use File.ReadAllText in C# to read all text from a file into a single string. Provide the file path as a string argument, and it returns the file content. This method is simple and useful for reading small to medium text files.
📐

Syntax

The File.ReadAllText method reads all text from a file and returns it as a string.

  • string path: The full path to the file you want to read.
  • Returns: A string containing the entire content of the file.
csharp
string content = File.ReadAllText(path);
💻

Example

This example shows how to read the content of a text file named example.txt and print it to the console.

csharp
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        // Read all text from the file
        string content = File.ReadAllText(filePath);

        // Print the content
        Console.WriteLine("File content:\n" + content);
    }
}
Output
File content: (This will show the full text inside example.txt)
⚠️

Common Pitfalls

Common mistakes when using File.ReadAllText include:

  • Providing an incorrect or relative file path that does not exist, causing a FileNotFoundException.
  • Not handling exceptions like IOException or UnauthorizedAccessException which can occur if the file is locked or access is denied.
  • Using ReadAllText for very large files, which can cause high memory usage.

Always ensure the file path is correct and consider using try-catch blocks to handle errors gracefully.

csharp
try
{
    string content = File.ReadAllText("wrongpath.txt");
    Console.WriteLine(content);
}
catch (Exception ex)
{
    Console.WriteLine("Error reading file: " + ex.Message);
}
Output
Error reading file: Could not find file 'wrongpath.txt'.
📊

Quick Reference

Summary tips for using File.ReadAllText:

  • Use full or relative file paths carefully.
  • Handle exceptions to avoid program crashes.
  • Best for small to medium text files.
  • Returns all file content as a single string.

Key Takeaways

File.ReadAllText reads the entire file content into a string in one call.
Always provide the correct file path and handle exceptions to avoid errors.
Use it for small or medium files to prevent high memory use.
Wrap calls in try-catch blocks to manage file access issues gracefully.