Reading Files in C#

Our first example demonstrates reading files in C#. Reading and writing files are basic tasks needed for many C# programs. Let’s look at some examples of reading files.

using System;
using System.IO;

class Program
{
    // This helper will streamline our error checks below.
    static void Check(Exception e)
    {
        if (e != null)
        {
            throw e;
        }
    }

    static void Main()
    {
        // Perhaps the most basic file reading task is
        // reading a file's entire contents into memory.
        try
        {
            string dat = File.ReadAllText("/tmp/dat");
            Console.Write(dat);
        }
        catch (Exception e)
        {
            Check(e);
        }

        // You'll often want more control over how and what
        // parts of a file are read. For these tasks, start
        // by opening a FileStream.
        using (FileStream f = File.OpenRead("/tmp/dat"))
        {
            // Read some bytes from the beginning of the file.
            // Allow up to 5 to be read but also note how many
            // actually were read.
            byte[] b1 = new byte[5];
            int n1 = f.Read(b1, 0, b1.Length);
            Console.WriteLine($"{n1} bytes: {System.Text.Encoding.UTF8.GetString(b1, 0, n1)}");

            // You can also Seek to a known location in the file
            // and Read from there.
            f.Seek(6, SeekOrigin.Begin);
            byte[] b2 = new byte[2];
            int n2 = f.Read(b2, 0, b2.Length);
            Console.WriteLine($"{n2} bytes @ {f.Position}: {System.Text.Encoding.UTF8.GetString(b2, 0, n2)}");

            // Seek relative to the current position,
            f.Seek(4, SeekOrigin.Current);

            // and relative to the end of the file.
            f.Seek(-10, SeekOrigin.End);

            // The StreamReader provides some helpful methods
            // for reading text files.
            f.Seek(6, SeekOrigin.Begin);
            using (StreamReader reader = new StreamReader(f))
            {
                char[] buffer = new char[2];
                int n3 = reader.Read(buffer, 0, buffer.Length);
                Console.WriteLine($"{n3} bytes @ {f.Position}: {new string(buffer)}");
            }

            // There is no built-in rewind, but
            // Seek(0, SeekOrigin.Begin) accomplishes this.
            f.Seek(0, SeekOrigin.Begin);

            // The StreamReader also provides a buffered reader
            // that may be useful both for its efficiency
            // with many small reads and because of the additional
            // reading methods it provides.
            using (StreamReader r4 = new StreamReader(f))
            {
                char[] peek = new char[5];
                r4.ReadBlock(peek, 0, 5);
                Console.WriteLine($"5 bytes: {new string(peek)}");
            }
        }
    }
}

To run the program, first create a file with some content:

$ echo "hello" > /tmp/dat
$ echo "C#" >>   /tmp/dat
$ dotnet run
hello
C#
5 bytes: hello
2 bytes @ 6: C#
2 bytes @ 6: C#
5 bytes: hello

This example demonstrates various ways to read files in C#, including reading entire files, seeking to specific positions, and using buffered readers. The using statement ensures that file resources are properly disposed of after use.

Next, we’ll look at writing files.