Ensure your specific path exists on the disk. Your program requires a certain directory, such as one that stores XML files, text files, or images, to be present. In the Open File dialog, we assume this folder is there, and we require it at startup.
Unfortunately, you can almost never be sure that a directory is present between runs of your application. The user may delete it, or it might be lost due to some other interaction on the system (such as a cleanup utility). Your installation or upgrade process might have mistakenly removed it.
The Paint.NET code I am showing requires that there be a palettes directory. (There are color files stored in this directory apparently.) To ensure that the directory exists, the code includes a method called EnsurePalettesPathExists, which is called in several places. Let's look at the implementation.
namespace PaintDotNet
{
internal sealed class PaletteCollection
{
public static void EnsurePalettesPathExists()
{
// Set to folder path we must ensure exists.
string palettesPath = PalettesPath;
try
{
// If the directory doesn't exist, create it.
if (!Directory.Exists(palettesPath))
{
Directory.CreateDirectory(palettesPath);
}
}
catch (Exception)
{
// Fail silently
}
}
}
}This code allows us to isolate some of the mundane file system problems from the other code. This method could still fail, but in most cases, it will accomplish its goal and ensure the path exists. Next I show how it is used in Paint.NET's Save File method. It is called at the start of the method, and it helps simplify the Save method.
public void Save()
{
EnsurePalettesPathExists();
string palettesPath = PalettesPath;
foreach (string paletteName in this.palettes.Keys)
{
// Code here...
}
}And the next caller I want to show in Paint.NET's source is an event handler that is called when the user opens a palette folder. (Obviously, if the user opens a folder, it must be there! This situation might be caused if the user deleted the folder in the meantime. Coding defensively is the finest skill of a programmer.)
namespace PaintDotNet
{
internal class ColorsForm : FloatingToolForm
{
private void OnOpenPalettesFolderClickedHandler(object sender, EventArgs e)
{
PaletteCollection.EnsurePalettesPathExists();
try
{
// Code...
}
catch (Exception)
{
// More error handling.
}
}
}
}This is a professional and tested way of ensuring that fewer IO problems arise. It is a safeguard and these sorts of checks are critical for user-centric programs. This program is a world-class drawing program that I run every day, and it never crashes.
Here we can follow the example of Paint.NET and ensure paths exist. It shows some examples of exception handling, and the Directory class in System.IO. Reduce code duplication with elegant methods that ensure certain conditions. In doing so, your program will be more resilient to user mistakes.