C# File Handling and Streams Explained

C# provides powerful APIs for working with files, directories, and streams. Developers can use these features to create, read, write, copy, move, and delete files in desktop, web, and server applications.

What is File Handling in C#?

File handling allows an application to store and retrieve data from files on the operating system. The System.IO namespace contains many of the classes used for file and directory operations.

CSHARP
using System.IO;

Creating a File

The File class provides simple methods for creating and managing files.

CSHARP
string path = "data.txt";

File.WriteAllText(path, "Hello from C#");

Reading a File

ReadAllText reads the complete contents of a text file into a string.

CSHARP
string content = File.ReadAllText("data.txt");

Console.WriteLine(content);

Writing Text to a File

WriteAllText creates a file or replaces its existing contents with the supplied text.

CSHARP
File.WriteAllText("notes.txt", "C# File Handling\nLearning Streams");

Appending Data

AppendAllText adds text to the end of an existing file instead of replacing its contents.

CSHARP
File.AppendAllText("notes.txt", "\nNew line added.");

Checking Whether a File Exists

File.Exists can be used to check whether a specified file is available before attempting an operation.

CSHARP
if (File.Exists("data.txt"))
{
    Console.WriteLine("File exists");
}

Copying, Moving, and Deleting Files

The File class also provides methods for common file management operations.

CSHARP
File.Copy("data.txt", "backup.txt", true);
File.Move("backup.txt", "archive.txt");
File.Delete("archive.txt");

Working with Directories

The Directory class is used to create, inspect, and remove directories.

CSHARP
Directory.CreateDirectory("Reports");

string[] files = Directory.GetFiles("Reports");

foreach (string file in files)
{
    Console.WriteLine(file);
}

File Handling Command Table

MethodPurposeExample
WriteAllTextWrite text to a fileFile.WriteAllText(...)
ReadAllTextRead text from a fileFile.ReadAllText(...)
AppendAllTextAppend textFile.AppendAllText(...)
CopyCopy a fileFile.Copy(...)
MoveMove or rename a fileFile.Move(...)
DeleteDelete a fileFile.Delete(...)
ExistsCheck file existenceFile.Exists(...)

Using StreamReader

StreamReader is useful for reading text from files incrementally instead of loading the entire file into memory at once.

CSHARP
using StreamReader reader = new StreamReader("data.txt");

string line;
while ((line = reader.ReadLine()) != null)
{
    Console.WriteLine(line);
}

Using StreamWriter

StreamWriter allows applications to write text to a stream, making it useful for creating logs and processing large amounts of text.

CSHARP
using StreamWriter writer = new StreamWriter("log.txt");

writer.WriteLine("Application started");
writer.WriteLine("Processing data...");

Using FileStream

FileStream provides lower-level access to file data as a stream of bytes. It can be useful when working with binary data or when more control over file I/O is required.

CSHARP
using FileStream stream = new FileStream(
    "data.bin",
    FileMode.Create,
    FileAccess.Write
);

byte[] data = { 10, 20, 30, 40 };
stream.Write(data, 0, data.Length);

Synchronous vs Asynchronous File Operations

FeatureSynchronousAsynchronous
ExecutionWaits for I/O to completeCan await I/O completion
ExampleFile.ReadAllTextFile.ReadAllTextAsync
Best ForSimple operationsResponsive and scalable applications

Asynchronous File Reading

Modern .NET provides asynchronous file APIs that can be useful when applications perform file I/O without wanting to block while waiting for the operation to complete.

CSHARP
string content = await File.ReadAllTextAsync("data.txt");
Console.WriteLine(content);

Handling File Exceptions

File operations can fail because of missing files, invalid paths, permissions, locked files, or other operating system conditions. Applications should handle expected failures appropriately.

CSHARP
try
{
    string content = File.ReadAllText("data.txt");
    Console.WriteLine(content);
}
catch (FileNotFoundException)
{
    Console.WriteLine("The file was not found.");
}
catch (UnauthorizedAccessException)
{
    Console.WriteLine("Access to the file was denied.");
}

Real-World Applications

  • Application logging
  • Configuration files
  • Report generation
  • CSV processing
  • Document management
  • Data import and export
  • Local application storage

Common Mistakes to Avoid

  • Using incorrect or hard-coded paths
  • Ignoring file access permissions
  • Loading very large files completely into memory
  • Forgetting to dispose streams
  • Overwriting important files accidentally
  • Ignoring file operation exceptions

Advanced File Handling Concepts

  • MemoryStream
  • BufferedStream
  • BinaryReader and BinaryWriter
  • FileSystemWatcher
  • Asynchronous streams
  • Path manipulation
  • File locking

Practice Exercises

  • Create a text file
  • Write and read user information
  • Append application logs
  • Copy a file to a backup directory
  • List files from a directory
  • Read a large file line by line
  • Build a simple text-file based notes application

Conclusion

C# provides a complete set of tools for file and directory operations. The File, Directory, StreamReader, StreamWriter, and FileStream APIs allow developers to build applications that efficiently work with text and binary data.

Note: Note: Always validate file paths, handle expected I/O errors, and dispose file streams properly when working with files.