Path exists. Does a specific path exist on the disk? Consider a C# program that requires a certain directory—it might store settings files, data or images.
With a special method, we can ensure a directory exists. This can make the program more reliable when it starts—the directory will always exist (in normal situations).
An example. We can almost never be sure that a directory is present. The user may delete it, or it might be lost due to some other interaction on the system.
Further Your installation or upgrade process might have mistakenly removed it, for reasons beyond your control.
However We can try to ensure a path exists, and create it if it doesn't, with a method similar to this one.
using System;
using System.IO;
class Program
{
public static void EnsurePathExists(string path)
{
// ... Set to folder path we must ensure exists.
try
{
// ... If the directory doesn't exist, create it.
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
catch (Exception)
{
// Fail silently.
}
}
static void Main()
{
// Test the method.
EnsurePathExists(@"C:\programs\exampledir\");
Console.WriteLine("DONE");
}
}DONE
Notes, above program. This method checks to see if the path exists. If the path does not exist, we attempt to create the location—we try to ensure the location exists.
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.
Notes, redundant check. The Directory.CreateDirectory method will do nothing if the directory already exists. So we do not need to call Directory.Exists first.
A summary. Here we ensure paths exist. It shows some examples of exception handling, and the Directory class in System.IO. The exception handling is not finished here.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 17, 2022 (simplify).