File handling in C# is one of the most important concepts in .NET application development. Whether you are building a console application, Windows Forms app, WPF application, ASP.NET Core web application, or enterprise-level software, reading and writing files is a fundamental requirement.
In this detailed guide, we will explore how to write to a file in C# and read from a file in C# using various classes available in the .NET framework. You will learn about the File class, StreamWriter, StreamReader, FileStream, file modes, exception handling, and best practices.
This tutorial focuses on practical implementation and real-world scenarios. By the end, you will have strong knowledge of:
File handling allows applications to:
Without file input and output (I/O), applications would lose all data once they stop running. Therefore, understanding C# file I/O is essential for every developer.
To perform file operations in C#, you must include the following namespace:
using System;
using System.IO;
The System.IO namespace provides classes for file and stream operations.
The File class provides static methods for creating, copying, deleting, reading, and writing files.
Used for reading and writing bytes to files.
Used for writing text to files.
Used for reading text from files.
This is the simplest way to write text into a file in C#. If the file does not exist, it will be created. If it exists, it will overwrite the content.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
string content = "Hello, this is C# file writing example.";
File.WriteAllText(path, content);
Console.WriteLine("File written successfully.");
}
}
This method is ideal for small files and quick operations.
Used when writing multiple lines at once.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
string[] lines = {
"First Line",
"Second Line",
"Third Line"
};
File.WriteAllLines(path, lines);
Console.WriteLine("Lines written successfully.");
}
}
StreamWriter gives more control over writing operations.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine("Welcome to C# File Handling");
writer.WriteLine("StreamWriter Example");
}
Console.WriteLine("File written using StreamWriter.");
}
}
The using statement ensures proper resource management by closing the stream automatically.
Appending means adding data to an existing file without deleting previous content.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine("This line is appended.");
}
Console.WriteLine("Data appended successfully.");
}
}
The second parameter set to true enables append mode.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
string content = File.ReadAllText(path);
Console.WriteLine(content);
}
}
This reads the entire file content as a single string.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
}
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
using (StreamReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
StreamReader is efficient for large files.
FileStream provides low-level file access for reading and writing bytes.
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
string path = "example.txt";
using (FileStream fs = new FileStream(path, FileMode.Create))
{
byte[] data = Encoding.UTF8.GetBytes("FileStream Example");
fs.Write(data, 0, data.Length);
}
Console.WriteLine("File written using FileStream.");
}
}
FileMode defines how a file should be opened:
Choosing the correct FileMode ensures safe file operations.
File operations may throw exceptions such as:
try
{
string content = File.ReadAllText("example.txt");
Console.WriteLine(content);
}
catch (FileNotFoundException ex)
{
Console.WriteLine("File not found: " + ex.Message);
}
catch (IOException ex)
{
Console.WriteLine("IO Error: " + ex.Message);
}
Always use try-catch blocks in production applications.
Async file operations improve performance in large applications.
using System;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string path = "example.txt";
await File.WriteAllTextAsync(path, "Async File Writing Example");
string content = await File.ReadAllTextAsync(path);
Console.WriteLine(content);
}
}
Async methods prevent UI blocking in desktop and web applications.
| Feature | File.WriteAllText | StreamWriter |
|---|---|---|
| Ease of Use | Very Simple | More Flexible |
| Performance | Good for small files | Better for large files |
| Control | Limited | More Control |
Understanding how to write to a file and read it in C# is essential for every .NET developer. Whether using File class methods for simple operations or StreamWriter and FileStream for advanced scenarios, C# provides powerful tools for file handling.
Mastering C# file I/O operations will help you build reliable applications capable of storing and retrieving data efficiently. Practice these examples and experiment with different file modes and stream techniques to strengthen your knowledge.
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved