Now before we attempt to create a directory, it is very easy to first validate whether or not the directory we wish to create in fact resides on the server by using the Directory.Exist method. This method accepts a string parameter, such as C:\MyDirectory, and returns a a Boolean value of true if the directory is found; otherwise, false is returned.
Be sure to wrap the code where you are attempting to create a directory within a try-catch block. This way you will know exactly if the class failed or ran successfully. The try-catch block is benefical in many aspects. Within the catch statement you can perform actions such as writing the failure to a flat file event log or the server's event log or even emailing a person or group if a failure occurs. However this is a topic within itself, and I just wanted to touch upon the power of using a try-catch statement.
using System;
using System.IO;
namespace SystemIO
{
/// <summary>
/// Summary description for article051604.
/// </summary>
public class article051604
{
static void Main(string[] args)
{
CreateDirectory();
}
public static void CreateDirectory()
{
string directoryPath = @"c:\MyDirectory";
try
{
if (System.IO.Directory.Exists(directoryPath))
{
Console.WriteLine("That directory path exists already.");
}
else
{
System.IO.Directory.CreateDirectory(directoryPath);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
As you can see in the code sample above, the Main method calls the CreateDirectory method. The first thing I did was to assign the directory I wish to establish to a string variable. Then I wrap my attempt to create this directory within a try-catch block, as I stated earlier.
Here, utilizing the Directory.Exist method, I first validate that the directory does or doesn't exist. If the directory is found to exist then I write a message to the console stating that "the directory path exists already"; otherwise, if the directory is not found, it is then created within the else statement. Finally, if anything went wrong, the catch statement will write the error message out to the console.