How to Write Files in C# Using File Handling
π Introduction: Why Write Files in C#?
Imagine you’re building a note-taking app where users save their notes to a file. Or maybe you’re developing a log system to keep track of important events. In both cases, you need file handling to write data to a file.
In this lesson, you’ll learn how to write files in C# using different methods. It’s easy, and I’ll guide you step by step! π
π What You Are Going to Learn in This Lesson?
βοΈ Learn how to write files in C# using StreamWriter
and File.WriteAllText()
.
βοΈ Understand different ways to write text to a file.
βοΈ See real-world examples to make learning fun.
βοΈ Get hands-on experience with simple and clear programs.
π Methods to Write Files in C#
There are multiple ways to write files in C#. Let’s explore them one by one.
Β
1οΈβ£ Using File.WriteAllText()
(Simplest Way!)
If you want a quick and easy way to write a small amount of text to a file, use File.WriteAllText()
.
π Syntax:
File.WriteAllText("filename.txt", "Your text here");
π Example:
using System;
using System.IO; // Required for File Handling
class Program
{
static void Main()
{
string filePath = "notes.txt";
string content = "Hello, this is my first note!";
try
{
File.WriteAllText(filePath, content);
Console.WriteLine("File written successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
π Output:
File written successfully!
π Explanation:
- The
File.WriteAllText()
method creates the file if it doesnβt exist and writes text into it. - If the file already exists, it overwrites the content.
- We use
try-catch
to handle any errors.
2οΈβ£ Using StreamWriter
(For Writing Multiple Lines)
If you need to write multiple lines to a file, StreamWriter
is a better option.
π Example:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "journal.txt";
try
{
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.WriteLine("Day 1: Learning C# is fun!");
sw.WriteLine("Day 2: I wrote my first program.");
sw.WriteLine("Day 3: Now, I can write files in C#!");
}
Console.WriteLine("File written successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
π Output:
File written successfully!
π Explanation:
StreamWriter
creates the file and writes multiple lines.- The
using
statement ensures the file closes properly after writing.
π Real-World Example: Writing a Log File
Imagine you are creating a banking system that logs every transaction. You can write these logs into a file for future reference.
π Example:
using System;
using System.IO;
class BankLogger
{
static void Main()
{
string logFile = "transaction_log.txt";
try
{
using (StreamWriter sw = new StreamWriter(logFile, true))
{
sw.WriteLine(DateTime.Now + " - $500 deposited to account.");
}
Console.WriteLine("Transaction logged successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
π Output (File Content in transaction_log.txt
):
2025-02-25 10:30 AM - $500 deposited to account.
π Explanation:
- The log file appends new transactions using
true
inStreamWriter(file, true)
. - This is useful for tracking user activity or storing system logs.
π― Summary: What Did You Learn?
β
You learned how to write files in C# using File.WriteAllText()
, StreamWriter
, and File.AppendAllText()
.
β
You saw a real-world example of logging transactions in a banking system.
β
Now, youβre ready to read files in C# in the next lesson.
β‘οΈ Next What?
Awesome! You just learned how to write files in C# using file handling. π
But what if you want to add more data to an existing file without overwriting it? π€
In the next chapter, you will learn how to append data to a file in C#. Stay tunedβit’s going to be super useful! ππ₯