Search⌘ K
AI Features

Reading Files

Explore how to read files using the FileStream class in C# and understand safe resource management with IDisposable and the using statement. Learn to handle file streams both synchronously and asynchronously while preventing memory leaks. Discover modern, high-level file reading methods with the System.IO.File class and path handling across platforms.

A common example of an unmanaged resource is a file residing on a disk. To open it, read it, write to it, or delete it, any programming language must ultimately settle with operating system calls. Because the operating system does not run on top of the CLR, OS calls are considered unmanaged code.

Therefore, we must appropriately dispose of objects that use such external calls. Before we start creating and disposing of file objects, we must first understand how .NET works with files.

The Stream class

A file is fundamentally nothing but a sequence of bytes. Depending on the file format, this sequence is interpreted differently, allowing the user to see meaningful output. Interpreting an image file's bytes as text results in invalid or unreadable characters.

In .NET, a sequence of bytes is represented by the Stream class inside the System.IO namespace. It is an abstract base class for all streams in .NET.

There are two main operations provided by streams:

  • Reading: This represents the transfer of bytes from the external environment (such as a file, a network connection, or a keyboard) into the program. For instance, we can read from the stream and save everything as an array of bytes (byte[]).

  • Writing: This represents the transfer of bytes from the application out to the external environment (from a byte[] to a file, network connection, or output device).

Depending on the source of a byte sequence, there are various Stream types in .NET. For network ...