.NET Filesystem Operations

The .NET platform provides a comprehensive set of classes for interacting with the filesystem. These classes are primarily found within the System.IO namespace and offer robust capabilities for managing files, directories, streams, and paths.

Core Concepts

System.IO Namespace

This namespace contains the fundamental types for file and directory operations. Key classes include:

Working with Files

Creating and Writing to Files

You can create new files or overwrite existing ones using methods like File.Create() and File.WriteAllText().

Example: Writing text to a file:

using System;
using System.IO;

public class FileWriteExample
{
    public static void Main(string[] args)
    {
        string filePath = "myDocument.txt";
        string content = "Hello, .NET Filesystem!";

        try
        {
            File.WriteAllText(filePath, content);
            Console.WriteLine($"Successfully wrote to: {Path.GetFullPath(filePath)}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Reading from Files

Reading file content can be done using methods like File.ReadAllText(), File.ReadAllLines(), or by using a StreamReader for more control.

Example: Reading text from a file:

using System;
using System.IO;

public class FileReadExample
{
    public static void Main(string[] args)
    {
        string filePath = "myDocument.txt";

        try
        {
            if (File.Exists(filePath))
            {
                string fileContent = File.ReadAllText(filePath);
                Console.WriteLine($"Content of {filePath}:\n{fileContent}");
            }
            else
            {
                Console.WriteLine($"File not found: {filePath}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

File Operations

Common file operations include:

Working with Directories

Creating and Deleting Directories

Use Directory.CreateDirectory() to create a directory and Directory.Delete() to remove one.

Example: Creating a directory:

using System;
using System.IO;

public class DirectoryCreateExample
{
    public static void Main(string[] args)
    {
        string dirPath = "myNewFolder";

        try
        {
            Directory.CreateDirectory(dirPath);
            Console.WriteLine($"Directory created: {Path.GetFullPath(dirPath)}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Enumerating Directories and Files

You can list the contents of a directory using Directory.GetFiles() and Directory.GetDirectories().

Example: Listing files in a directory:

using System;
using System.IO;

public class DirectoryListExample
{
    public static void Main(string[] args)
    {
        string dirPath = "."; // Current directory

        try
        {
            Console.WriteLine($"Files in '{Path.GetFullPath(dirPath)}':");
            string[] files = Directory.GetFiles(dirPath);
            foreach (string file in files)
            {
                Console.WriteLine($"- {Path.GetFileName(file)}");
            }

            Console.WriteLine($"\nSubdirectories in '{Path.GetFullPath(dirPath)}':");
            string[] subdirs = Directory.GetDirectories(dirPath);
            foreach (string subdir in subdirs)
            {
                Console.WriteLine($"- {Path.GetFileName(subdir)}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Path Manipulation

The Path class is essential for creating platform-agnostic paths. It handles nuances like directory separators (\ vs /).

Common Path Methods:

Method Description
Path.Combine(path1, path2, ...) Combines multiple path segments into a single path.
Path.GetFileName(path) Returns the file name and extension of a path string.
Path.GetDirectoryName(path) Returns the directory information for a path string.
Path.GetExtension(path) Returns the extension of a path string.
Path.HasExtension(path) Determines whether a path string contains a file extension.
Path.GetFullPath(path) Gets the full, absolute path for the specified path string.

Streams and Buffering

For efficient reading and writing, especially large files, using FileStream with appropriate buffering is recommended. StreamReader and StreamWriter wrap FileStream to provide convenient text-based I/O.

Example: Using StreamReader:

using System;
using System.IO;

public class StreamReaderExample
{
    public static void Main(string[] args)
    {
        string filePath = "myDocument.txt";

        try
        {
            if (File.Exists(filePath))
            {
                using (StreamReader reader = new StreamReader(filePath))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            else
            {
                Console.WriteLine($"File not found: {filePath}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Error Handling

Filesystem operations can fail for various reasons (permissions, disk full, file not found, etc.). Always wrap your I/O operations in try-catch blocks to handle exceptions gracefully.

Common exceptions include:

The .NET filesystem API is a powerful tool for managing data persistence. By understanding these core components and best practices, you can effectively interact with the filesystem in your applications.