File Handling in C#: Reading/Writing Files, System.IO Classes & Best Practices

1. File Handling in C#

Q: What is file handling in C#?

File handling in C# involves reading from and writing to files, as well as managing files and directories. It is performed using classes in the System.IO namespace, such as File, FileStream, StreamReader, StreamWriter, Directory, and DirectoryInfo. C# provides high-level, managed APIs for safe and efficient file operations.

Q: Why is file handling important?

Q: How does file handling in C# differ from C/C++?

2. Reading from and Writing to Files

Q: How do you read from a file in C#?

Reading from a file can be done using:

Q: How do you write to a file in C#?

Writing to a file can be done using:

Q: Can you give an example of reading from and writing to files in C#?

using System;
using System.IO;

namespace FileReadWrite
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "example.txt";

            // Writing to a file
            try
            {
                // Using File.WriteAllText (overwrites file)
                File.WriteAllText(filePath, "Hello, C# File Handling!\n");

                // Using StreamWriter to append
                using (StreamWriter writer = new StreamWriter(filePath, append: true))
                {
                    writer.WriteLine("Appending a new line.");
                }
                Console.WriteLine("Successfully wrote to file.");
            }
            catch (IOException ex)
            {
                Console.WriteLine($"Write error: {ex.Message}");
            }

            // Reading from a file
            try
            {
                // Using File.ReadAllText
                string content = File.ReadAllText(filePath);
                Console.WriteLine("\nFile content (ReadAllText):");
                Console.WriteLine(content);

                // Using StreamReader to read line-by-line
                Console.WriteLine("File content (StreamReader):");
                using (StreamReader reader = new StreamReader(filePath))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine($"Read error: {ex.Message}");
            }
        }
    }
}

Output:

Successfully wrote to file.

File content (ReadAllText):
Hello, C# File Handling!
Appending a new line.

File content (StreamReader):
Hello, C# File Handling!
Appending a new line.

3. File and Directory Classes

Q: What are the key file and directory classes in C#?

The System.IO namespace provides classes for file and directory operations:

Q: What is the difference between File/FileInfo and Directory/DirectoryInfo?

File vs. FileInfo:

Directory vs. DirectoryInfo:

Use Case: Use static classes (File, Directory) for simple tasks; use instance-based (FileInfo, DirectoryInfo) for repeated operations or when accessing properties.

Q: Can you give an example of using File, FileInfo, Directory, and DirectoryInfo in C#?

using System;
using System.IO;

namespace FileDirectoryClasses
{
    class Program
    {
        static void Main(string[] args)
        {
            string dirPath = "TestFolder";
            string filePath = Path.Combine(dirPath, "test.txt");

            try
            {
                // Directory: Create directory
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                    Console.WriteLine($"Created directory: {dirPath}");
                }

                // File: Write to file
                File.WriteAllText(filePath, "Hello, File and Directory Classes!");
                Console.WriteLine($"Wrote to file: {filePath}");

                // FileInfo: Check file properties
                FileInfo fileInfo = new FileInfo(filePath);
                Console.WriteLine($"File size: {fileInfo.Length} bytes");
                Console.WriteLine($"Last modified: {fileInfo.LastWriteTime}");

                // DirectoryInfo: List files in directory
                DirectoryInfo dirInfo = new DirectoryInfo(dirPath);
                Console.WriteLine("\nFiles in directory:");
                foreach (FileInfo file in dirInfo.GetFiles())
                {
                    Console.WriteLine($"  {file.Name}");
                }

                // Clean up
                File.Delete(filePath);
                Directory.Delete(dirPath);
                Console.WriteLine("\nCleaned up: Deleted file and directory.");
            }
            catch (IOException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
}

Output:

Created directory: TestFolder
Wrote to file: TestFolder\test.txt
File size: 33 bytes
Last modified: [current timestamp]

Files in directory:
  test.txt

Cleaned up: Deleted file and directory.

Q: How do file and directory operations in C# differ from C/C++?

Q: What are common mistakes with file handling in C#?

Reading/Writing:

File/Directory Classes:

General:

Q: What are best practices for file handling in C#?

Reading/Writing:

File/Directory Classes:

General:

Frequently asked questions

What is file handling in C#?

File handling in C# involves reading from and writing to files, as well as managing files and directories using classes in the System.IO namespace like File, file stream, StreamReader, StreamWriter, Directory, and DirectoryInfo.

How do you read from a file in C#?

Use high-level methods like File.ReadAllText or File.ReadAllLines, or StreamReader for line-by-line/incremental reading. Always use 'using' for proper resource disposal.

How do you write to a file in C#?

Use File.WriteAllText/WriteAllLines for simple writes, or StreamWriter for incremental/appending writes. Specify append: true for appending.

What are the key file and directory classes in C#?

Key classes include File (static operations), FileInfo (instance-based), Directory (static), DirectoryInfo (instance-based), StreamReader/Writer, and file stream.

What is the difference between File and FileInfo in C#?

File is static for one-off operations; FileInfo is instance-based, better for repeated operations on the same file (e.g., checking properties like Length).

What are best practices for file handling in C#?

Use 'using' for automatic cleanup, handle exceptions, prefer asynchronous methods for I/O, check existence before operations, and use Path.Combine for paths.

What are common mistakes in file handling in C#?

Not using 'using' (resource leaks), forgetting exception handling, reading large files entirely into memory, and incorrect path handling.

How does file handling in C# differ from C/C++?

C# is managed, safer with automatic cleanup and exceptions; C/C++ is unmanaged, requires manual resource management with lower-level functions.