File Handling in C#: Reading and Writing Files
Introduction
File handling is one of the foundational tasks every C# developer should learn. Whether you're building desktop applications, APIs, or automation tools, reading and writing files is a core skill that enables data storage, processing, and communication. In this blog, we’ll explore **how to perform file handling in C#**, including reading, writing, appending, working with binary files, and managing file metadata.
What Is File Handling?
File handling refers to performing operations like creating, reading, writing, deleting, and modifying files. In C#, these operations are primarily performed using:
FileclassFileInfoclassStreamReaderandStreamWriterBinaryReaderandBinaryWriterFileStream
Reading Files in C#
The easiest way to read files in C# is using the File.ReadAllText and
File.ReadAllLines methods.
Example: Read Entire File
string content = File.ReadAllText("sample.txt");
Console.WriteLine(content);
Example: Read Line-by-Line
string[] lines = File.ReadAllLines("sample.txt");
foreach (var line in lines)
{
Console.WriteLine(line);
}
Writing Files in C#
To write data to a file, use File.WriteAllText or StreamWriter.
Example: Write Text to File
File.WriteAllText("output.txt", "Hello from C#!");
Using StreamWriter
using (StreamWriter writer = new StreamWriter("output.txt"))
{
writer.WriteLine("First line");
writer.WriteLine("Second line");
}
Appending Data to Files
File.AppendAllText("output.txt", "New line added!");
Working With Binary Files in C#
C# provides BinaryWriter and BinaryReader for binary data.
Write Binary Data
using (BinaryWriter writer = new BinaryWriter(File.Open("data.bin", FileMode.Create)))
{
writer.Write(25);
writer.Write(45.78);
writer.Write("Hello");
}
Read Binary Data
using (BinaryReader reader = new BinaryReader(File.Open("data.bin", FileMode.Open)))
{
int number = reader.ReadInt32();
double value = reader.ReadDouble();
string text = reader.ReadString();
}
Checking File Information With FileInfo
FileInfo file = new FileInfo("sample.txt");
Console.WriteLine(file.Name);
Console.WriteLine(file.Length);
Console.WriteLine(file.CreationTime);
Console.WriteLine(file.LastWriteTime);
Handling Exceptions in File Handling
try
{
string data = File.ReadAllText("unknown.txt");
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found!");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Permission denied!");
}
catch (Exception ex)
{
Console.WriteLine("Unexpected error: " + ex.Message);
}
Real-World Applications of File Handling
- Reading configuration files
- Logging user actions
- Importing/exporting data
- Generating reports
- Automating file-based workflows
Conclusion
File handling is a crucial skill for any C# developer. Understanding how to read, write, append, and manage files unlocks new possibilities for application development. Start applying these concepts in your own projects and build more powerful software.
This Content Sponsored by SBO Digital Marketing. Mobile-Based Part-Time Job Opportunity by SBO! Earn money online by doing simple content publishing and sharing tasks. Here's how: Job Type: Mobile-based part-time work Work Involves: Content publishing Content sharing on social media Time Required: As little as 1 hour a day Earnings: ₹300 or more daily Requirements: Active Facebook and Instagram account Basic knowledge of using mobile and social media For more details: WhatsApp your Name and Qualification to 9025032394 a.Online Part Time Jobs from Home b.Work from Home Jobs Without Investment c.Freelance Jobs Online for Students d.Mobile Based Online Jobs e.Daily Payment Online Jobs Keyword & Tag: #OnlinePartTimeJob #WorkFromHome #EarnMoneyOnline #PartTimeJob #jobs #jobalerts #withoutinvestmentjob


0 Comments