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: