...

/

Reading Files

Reading Files

Read files without causing memory leaks.

Introduction

The best example of an unmanaged resource is a file that resides 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 doesn’t run on top of the CLR, OS calls are considered unmanaged code. Therefore, we must dispose of objects that use such external calls appropriately. Before we start the creation and disposal of file objects, we must first understand how .NET works with files.

The Stream class

A file is nothing but a sequence of bytes. Depending on the file format, this sequence is interpreted differently and the user sees a meaningful output. If we interpret an image as a text, then we get some gibberish output.

In .NET, a sequence of bytes is represented by the Stream class inside the System.IO namespace. It’s an abstract base class for all streams inside .NET. There are two main operations provided by ...