MSDN Documentation

File Input and Output (I/O) in .NET

This document provides a comprehensive guide to performing file input and output operations in .NET. Learn how to read from, write to, and manage files and directories efficiently and securely.

Core Concepts

Key Classes and Namespaces

The primary classes and namespaces for file I/O reside in the System.IO namespace.

For a detailed list, refer to the .NET API Browser for System.IO.

Code Examples

Reading Text from a File

Using StreamReader:

using System;
using System.IO;

public class ReadTextFile
{
    public static void Main(string[] args)
    {
        string filePath = "myFile.txt";
        try
        {
            using (StreamReader sr = new StreamReader(filePath))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"The file could not be read: {e.Message}");
        }
    }
}

Alternatively, using the static File.ReadAllText():

string content = File.ReadAllText("myFile.txt");
Console.WriteLine(content);

Writing Text to a File

Using StreamWriter:

using System;
using System.IO;

public class WriteTextFile
{
    public static void Main(string[] args)
    {
        string filePath = "output.txt";
        try
        {
            using (StreamWriter sw = new StreamWriter(filePath))
            {
                sw.WriteLine("This is the first line.");
                sw.WriteLine("This is the second line.");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"The file could not be written: {e.Message}");
        }
    }
}

To append to a file, use new StreamWriter(filePath, true) or File.AppendAllText().

File.AppendAllText("output.txt", "This line is appended.");

Checking if a File Exists

if (File.Exists("myFile.txt"))
{
    Console.WriteLine("File exists.");
}
else
{
    Console.WriteLine("File does not exist.");
}

Creating a Directory

string directoryPath = "MyNewFolder";
if (!Directory.Exists(directoryPath))
{
    Directory.CreateDirectory(directoryPath);
    Console.WriteLine($"Directory '{directoryPath}' created.");
}

Best Practices and Considerations