Search⌘ K
AI Features

Reading Files

Explore effective file reading techniques in C# with FileStream and the .NET framework. Understand how to check file existence, read data safely, dispose of unmanaged resources properly using the IDisposable interface, and utilize modern methods like File.ReadAllTextAsync for efficient and reliable file 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 access, we have NetworkStream, and for files, we have FileStream. In this lesson, we are interested in the latter. ...