Complete C# Tutorial

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! 😊

πŸ“Œ 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 in StreamWriter(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! πŸš€πŸ”₯

Leave a Comment

Share this Doc

Writing to Files in C#

Or copy link