C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Your program requires a certain directory—such as one that stores XML files, text files or images—to be present. We see how a popular application ensures that paths exist.
Example. 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.
Note: Your installation or upgrade process might have mistakenly removed it, for reasons beyond your control.
Example code from Paint.NET: C# 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 } } } }
Logic deals with directory. This method simply checks to see if the path exists, and if it doesn't, it tries to create the location. It tries to ensure the location exists—if it is at all possible to ensure that.
Also: The code catches it own exceptions when it cannot do its job. We should use exceptions when code cannot do what it needs to do.
Directory: This is a static class in the IO namespace. You can call Exists and CreateDirectory on it.
Example 2. 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.
Example method from Paint.NET: C# public void Save() { EnsurePalettesPathExists(); string palettesPath = PalettesPath; foreach (string paletteName in this.palettes.Keys) { // Code here... } }
Summary. 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.
And: In doing so, your program will be more resilient to user mistakes and other possible errors.