When preparing for C# interview topics, one crucial area that often comes up is file handling and streams. Many applications need to read and write data efficiently, making it essential for developers to understand how to work with files in C#.
In this blog, we will cover:
File handling basics in C#
Different ways to read and write files
Working with streams
Best practices for handling files efficiently
Common C# interview questions on file handling
C# provides built-in classes within the System.IO namespace for handling files and streams. The main classes include:
File and FileInfo – Provide static and instance-based methods for file operations.
Directory and DirectoryInfo – Manage directory structures.
StreamReader and StreamWriter – Handle reading and writing text files.
FileStream – Offers low-level file manipulation with buffering.
BinaryReader and BinaryWriter – Read and write binary data.
Understanding these classes will help you optimize file operations and answer interview questions confidently.
The File class provides simple static methods for reading and writing files.
Reading a File Using File.ReadAllText()
using System;
using System.IO;
class Program
{
static void Main()
{
string content = File.ReadAllText("example.txt");
Console.WriteLine(content);
}
}
Pros: Quick and easy.
Cons: Loads the entire file into memory, which is inefficient for large files.
Writing a File Using File.WriteAllText()
File.WriteAllText("example.txt", "Hello, C#!");
This method overwrites the existing file content.
Use File.AppendAllText() to add content instead of overwriting.
For reading and writing large files, StreamReader and StreamWriter are better than File.ReadAllText().
Reading a File Using StreamReader
using (StreamReader reader = new StreamReader("example.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Advantage: Reads file line by line, avoiding memory overload.
Common interview question: What’s the difference between ReadAllText() and StreamReader?
Writing a File Using StreamWriter
using (StreamWriter writer = new StreamWriter("example.txt"))
{
writer.WriteLine("This is a new line!");
}
Using using ensures automatic disposal of resources.
You can append data using new StreamWriter("example.txt", true).
FileStream is useful for reading and writing bytes efficiently.
Reading a File Using FileStream
using (FileStream fs = new FileStream("example.txt", FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string content = System.Text.Encoding.UTF8.GetString(buffer);
Console.WriteLine(content);
}
Interview tip: FileStream provides better control over file access than StreamReader.
Writing a File Using FileStream
using (FileStream fs = new FileStream("example.txt", FileMode.Create, FileAccess.Write))
{
byte[] data = System.Text.Encoding.UTF8.GetBytes("FileStream example in C#");
fs.Write(data, 0, data.Length);
}
FileMode.Create ensures the file is created or overwritten.
Sometimes, interviews may ask about binary file handling, which is common in images, audio, or serialized objects.
Writing Binary Data Using BinaryWriter
using (BinaryWriter writer = new BinaryWriter(File.Open("data.bin", FileMode.Create)))
{
writer.Write(42); // Writing an integer
writer.Write(3.14); // Writing a double
writer.Write("Hello C#"); // Writing a string
}
Reading Binary Data Using BinaryReader
using (BinaryReader reader = new BinaryReader(File.Open("data.bin", FileMode.Open)))
{
int number = reader.ReadInt32();
double pi = reader.ReadDouble();
string message = reader.ReadString();
Console.WriteLine($"Int: {number}, Double: {pi}, String: {message}");
}
Interview question: When would you use BinaryWriter over StreamWriter?
Answer: When dealing with non-text data like images, encrypted files, or serialized objects.
Use using statements for resource management to prevent memory leaks.
Prefer StreamReader and StreamWriter for large files instead of File.ReadAllText().
Handle exceptions properly using try-catch to avoid crashes.
Check file existence using File.Exists("example.txt") before reading.
Use async file operations (ReadAllTextAsync()) for non-blocking operations.
Answer:
File – Provides static methods for quick file operations.
FileInfo – Similar to File but provides instance-based methods with better performance for multiple operations.
FileStream – Offers advanced control over file I/O, reading and writing in chunks.
Answer:
Use StreamReader when reading large files to avoid loading everything into memory at once.
Answer:
Use FileShare.ReadWrite when opening a file to allow concurrent access.
Handle exceptions using try-catch for IOException.
Answer:
FileStream reads bytes directly and offers better performance for binary data like images or videos.
Understanding file handling and streams is essential for C# interviews, especially for roles involving data processing, logging, and performance optimization.
To summarize:
Use File for quick file operations.
Prefer StreamReader and StreamWriter for large text files.
Use FileStream and BinaryReader/BinaryWriter for low-level file manipulation.
Follow best practices like exception handling and using statements.
By mastering these concepts, you'll be well-prepared for any C# interview topics related to file handling.