14 Files and exceptions 

 

This chapter covers

  • Working with files on a low level
  • Reading byte-level data from a file
  • Exploring the filesystem and dealing with exceptions
  • Defining, throwing, and catching exceptions

So far in this book, we have covered projects that dealt with reading data, transforming it, and providing some kind of output. We were mostly interested in the “happy path,” keeping interactions with the environment to a minimum, so we didn’t have to worry about dealing with erroneous behavior. That will change with this chapter.

The project we want to take a look at is a file syncing utility that will copy files and directory structures from one directory to another, only copying files that are not already present at the target directory. This will require us to learn about exceptions and how to handle them, which is what this chapter is about.

14.1 Opening and reading files

Sometimes, we want to keep two directory structures in sync, whether as a backup, as a way of keeping files on a network-attached storage, or to sync files between staging and production environments. A common tool for this task is rsync. However, we want to try our hand at creating such a tool ourselves. It should be capable of traversing a directory structure as well as copying missing and changed files to a destination, which is shown in figure 14.1. If a file is present at the destination but not the source, we simply ignore it and do not delete or move it.

14.1.1 System.IO and Handle

14.1.2 Buffering and Seeking

14.2 Reading bytes from a file

14.2.1 Resource acquisition and bracket

14.3 Working with the filesystem and exceptions

14.3.1 System.Directory and System.FilePath

14.3.2 Listing files and directories

14.3.3 The basics of exceptions

14.4 Throwing and catching exceptions

14.4.1 Handling an error

Summary