c sharp

How to Create Directories Conditionally with C#

File operations is one of the most common and fundamental task for any developer. You will often find yourself needing to create, delete, or modify the files and directories within a given file system.

However, it is good to ensure that a directory exists before performing any operation. This ensures that you do not encounter errors during subsequent file operations.

In this post, we will discuss the various methods and techniques that we can use to conditionally create directories in C#.

Create a Directory in C#

In C#, we can create a directory using the “CreateDirectory” method from the “Directory” class. Hence, we need to import the “System.IO” namespace which gives us access to the “Directory” class.

The following example code demonstrates how to use the “CreateDirectory” method to create directories and subdirectories that are specified in the path, unless they already exist:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = @"C:\sample\linuxhint";
        Directory.CreateDirectory(path);
        Console.WriteLine("Dir created or exists");
    }
}

In the given example, we start by specifying the path to which we wish to create the new directory. We then use the CreateDirectory() method to pass the path that we previously defined. This should create the specified directory and any other subsequent directories that are specified in the path.

Conditional Checking

As we learned from the previous example, the Directory.CreateDirectory() method provides a simplistic way of creating directories within the filesystem. However, we may need to check if a directory exists before attempting to create it.

We can do this using the Exists() method from the “Directory” class. This method returns a Boolean value which we can use in an “if” clause.

Consider the following example code:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = @"C:\sample\linuxhint";

        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
            Console.WriteLine("Dir created");
        }
        else
        {
            Console.WriteLine("Dir already exists");
        }
    }
}

The resulting output is as follows:

Dir already exists

Conclusion

This tutorial covers the basics of using the System.IO namespace and the “Directory” class to create directories in C#.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list