Introduction

File handling is an essential skill for any programmer. In C#, working with files and streams allows you to read from and write to files, manage file systems, and handle data streams efficiently. This post will cover the basics of file handling, including reading and writing files, using streams, and handling common file I/O operations.

Reading from a File in C#

Reading from a file is a common task that can be accomplished using the System.IO namespace. The following example demonstrates how to read all lines from a file.

Example:

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        string path = "example.txt";

        if (File.Exists(path))
        {
            string[] lines = File.ReadAllLines(path);
            Console.WriteLine("Contents of example.txt:");
            foreach (string line in lines)
            {
                Console.WriteLine(line);
            }
        }
        else
        {
            Console.WriteLine("File not found.");
        }
    }
}

Explanation:

  • File.Exists: Checks if the file exists at the specified path.
  • File.ReadAllLines: Reads all lines from the file into a string array.
  • foreach Loop: Iterates through each line and prints it to the console.

Output (if example.txt contains text):

Contents of example.txt:
Line 1
Line 2
Line 3

Writing to a File in C#

Writing to a file can be easily done using methods provided by the System.IO namespace.

Example:

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        string path = "example.txt";
        string[] lines = { "First line", "Second line", "Third line" };

        File.WriteAllLines(path, lines);
        Console.WriteLine("Lines written to example.txt");
    }
}

Explanation:

  • File.WriteAllLines: Writes an array of strings to the file. If the file does not exist, it creates the file; otherwise, it overwrites the existing file.

Output:

Lines written to example.txt

Using Streams for File I/O

Streams provide a more flexible way to read from and write to files. They are useful for handling large files or binary data.

Reading a File with Streams:

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        string path = "example.txt";

        if (File.Exists(path))
        {
            using (StreamReader sr = new StreamReader(path))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        else
        {
            Console.WriteLine("File not found.");
        }
    }
}

Explanation:

  • StreamReader: Reads characters from a byte stream in a particular encoding.
  • using Statement: Ensures the stream is closed and resources are released after the operations are complete.
  • sr.ReadLine: Reads a line of characters from the stream.

Writing to a File with Streams:

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        string path = "example.txt";

        using (StreamWriter sw = new StreamWriter(path))
        {
            sw.WriteLine("First line");
            sw.WriteLine("Second line");
            sw.WriteLine("Third line");
        }
        Console.WriteLine("Lines written to example.txt using StreamWriter");
    }
}

Explanation:

  • StreamWriter: Writes characters to a stream in a particular encoding.
  • sw.WriteLine: Writes a line of text to the stream.

Output:

Lines written to example.txt using StreamWriter

Handling Binary Data with Streams

For binary data, you can use BinaryReader and BinaryWriter.

Example:

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        string path = "example.bin";

        // Writing binary data
        using (BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create)))
        {
            writer.Write(1.25);
            writer.Write("Hello");
            writer.Write(true);
        }
        Console.WriteLine("Binary data written to example.bin");

        // Reading binary data
        using (BinaryReader reader = new BinaryReader(File.Open(path, FileMode.Open)))
        {
            double a = reader.ReadDouble();
            string b = reader.ReadString();
            bool c = reader.ReadBoolean();

            Console.WriteLine($"Read from binary file: {a}, {b}, {c}");
        }
    }
}

Explanation:

  • BinaryWriter: Writes primitive types in binary to a stream.
  • BinaryReader: Reads primitive data types from a binary stream.
  • writer.Write and reader.Read: Methods for writing to and reading from a binary file.

Output:

Binary data written to example.bin
Read from binary file: 1.25, Hello, True

Conclusion

Mastering file handling in C# allows you to manage data storage efficiently, handle file systems, and process data streams. By understanding how to read from and write to files, use streams, and handle binary data, you can build robust applications that interact with the file system seamlessly.

Similar Posts