Lesson: C# File I/O

Introduction to File I/O

In C#, File I/O (Input/Output) refers to reading from and writing to files. The .NET framework provides several classes in the `System.IO` namespace that allow you to perform file operations like reading, writing, and manipulating files.

Reading Files in C#

To read from a file, we can use the `StreamReader` class, which provides methods to read text from a file line by line or as a whole.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";
        try
        {
            using (StreamReader reader = new StreamReader(filePath))
            {
                string content = reader.ReadToEnd();
                Console.WriteLine(content);
            }
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine("File not found: " + ex.Message);
        }
    }
}

In the code above, we open the file "example.txt" and read its content using `StreamReader`. If the file does not exist, a `FileNotFoundException` is thrown.

Writing Files in C#

To write to a file, we can use the `StreamWriter` class. This allows us to write text to a file, either by overwriting it or appending to it.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";
        try
        {
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.WriteLine("Hello, world!");
            }
        }
        catch (IOException ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

In this example, we use `StreamWriter` to write "Hello, world!" to the file "example.txt". If the file does not exist, it will be created. If it already exists, it will be overwritten.

Appending to Files in C#

To append to a file, we can use the `StreamWriter` class with the second parameter set to `true`, which tells the program to append instead of overwrite.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";
        try
        {
            using (StreamWriter writer = new StreamWriter(filePath, true))
            {
                writer.WriteLine("Appended text.");
            }
        }
        catch (IOException ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

Here, we use `StreamWriter(filePath, true)` to append the text "Appended text." to the existing file "example.txt".

Interactive Example: Write and Read a File

Let's try writing and reading a file with the following input:




Content of the file:



        

        

Deleting Files in C#

To delete a file in C#, we can use the `File.Delete()` method. If the file does not exist, no exception will be thrown, but nothing will happen.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";
        try
        {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
                Console.WriteLine("File deleted.");
            }
            else
            {
                Console.WriteLine("File not found.");
            }
        }
        catch (IOException ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

In the above code, we check if the file exists and delete it using `File.Delete()`. If the file is not found, we print an appropriate message.

File Operations Quiz

Test your knowledge on C# file I/O!

1. Which class is used to read from a file in C#?




2. What will happen if you try to read from a file that doesn't exist?




3. How do you append content to an existing file?




4. What method do you use to delete a file in C#?




5. Which exception is thrown when attempting to open a non-existent file for reading?