Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

File Streams in C#

Introduction

File streams in C# allow you to read from and write to files. Utilizing the System.IO namespace, you can perform operations such as creating, reading, writing, and closing files. This tutorial will guide you through the basics of file streams, with examples to solidify your understanding.

Basic Concepts

Before diving into examples, let's cover some key concepts:

  • Stream: Represents a sequence of bytes. It is the base class for all streams.
  • FileStream: Provides a Stream for file operations, allowing for both synchronous and asynchronous reading and writing.
  • StreamReader: Helps in reading characters from a byte stream in a particular encoding.
  • StreamWriter: Helps in writing characters to a stream in a particular encoding.

Creating and Writing to a File

To create and write to a file, you can use the FileStream and StreamWriter classes. Below is an example:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        using (FileStream fs = new FileStream(path, FileMode.Create))
        using (StreamWriter writer = new StreamWriter(fs))
        {
            writer.WriteLine("Hello, File Streams!");
            writer.WriteLine("This is an example of writing to a file.");
        }
        Console.WriteLine("File written successfully.");
    }
}

In this example, we create a file named example.txt and write two lines of text to it. The using statement ensures that the file is properly closed and resources are released when done.

Reading from a File

To read from a file, you can use the FileStream and StreamReader classes. Below is an example:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
        using (StreamReader reader = new StreamReader(fs))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

In this example, we open the file example.txt and read each line until the end of the file is reached. Each line is then printed to the console.

Appending to a File

To append to an existing file, you can open the file in append mode. Here is an example:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        using (FileStream fs = new FileStream(path, FileMode.Append))
        using (StreamWriter writer = new StreamWriter(fs))
        {
            writer.WriteLine("This line is appended.");
        }
        Console.WriteLine("Line appended successfully.");
    }
}

In this example, we open example.txt in append mode and add a new line of text at the end of the file.

Exception Handling

When working with file streams, it's essential to handle exceptions to ensure your application can gracefully handle errors. Below is an example that demonstrates exception handling:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        try
        {
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            using (StreamReader reader = new StreamReader(fs))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine($"File not found: {e.Message}");
        }
        catch (IOException e)
        {
            Console.WriteLine($"IO Exception: {e.Message}");
        }
        catch (Exception e)
        {
            Console.WriteLine($"Unexpected error: {e.Message}");
        }
    }
}

In this example, we use a try-catch block to handle potential exceptions that may occur during file operations.

Conclusion

File streams are an essential part of C# programming, enabling you to perform a wide range of file operations. By understanding and utilizing the FileStream, StreamReader, and StreamWriter classes, you can efficiently handle files in your applications. This tutorial covered the basic operations of creating, writing, reading, appending, and handling exceptions with file streams in C#. Practice these concepts to become proficient in file handling in C#.