Create a Directory

InterServer Web Hosting and VPS

Create a Directory

Here we'll look at a way of creating directories (sometimes called folders) on the file system in C#. (.NET 2.0)

There maybe times when you need to create a directory from code in C#. For instance, if you had a program which involved registering users, each user uploaded files, and you wanted each user to have their own seperate folder. Rather than manually creating folders using Windows Explorer, you could have your program create directories by itself whenever it needed to.

The System.IO namespace includes some classes for working with the filesystem, System.IO.Directory and System.IO.File amongst them are quite useful.

To create a directory through C#, you'll need to use the System.IO.Directory namespace. In order to be able to use this class, you'll need to call in the System.IO namespace first:

using System.IO;

With this namespace we can now access the Directory class. The following example shows how to check to see if a directory exists, and then if the directory does not exist, we then create the directory on the file system. Note how we use a literal string to prevent treating certain characters which appear in a filepath as escape characters.

// declare the directory path
string _directoryName = @"C:\test\directory-test";

// check folder exists
if (Directory.Exists(_directoryName))
   // ok, the directory exists
// if not then create

Sponsored Links
SolarSystem - AngularJS Demo
SolarSystem - Angular JS Demo

Check out my first Angular JS demo hosted in Azure, it helped win my first Angular contract. Put the sound on.