AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=458&pId=-1
Managing Directories in .NET
page
by Steven Swafford
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 19252/ 28

Creating a Directory

System.IO provides all the necessary classes, methods, and properties for manipulating directories and files.  In order to utilize the various methods within System.IO, users attempting to perform these operations must also have the required permissions to accomplish these types of actions; if they do not, a SecurityException will be thrown.  Below you will find the main classes under this namespace.

Class Purpose/Use
1. BinaryReader and BinaryWriter - Read and write binary data.
2. Directory, File, DirectoryInfo, and FileInfo - Create, delete, and move files or directories. You can retrieve specific information about the files or folder by using of the properties defined in these classes.
3. FileStream -  Access the files in a random order.
4. MemoryStream - Access data stored in memory.
5. StreamWriter and StreamReader - Read and write textual information.
6. StringReader and StringWriter - Read and write textual Information from a string buffer.

If you have ever run across a requirement to create a directory on the server running your application, the System.IO namespace provides everything you need to accomplish such a task. Here I will show you two way to create a directory named MyDirectory on the C: Drive.

using System;
using System.IO;


namespace SystemIO
{
 /// <summary>
 /// Summary description for article051604.
 /// </summary>
 public class article051604
 {


  static void Main(string[] args)
  {
   CreateDirectory1();
  }


  public static void CreateDirectory1()
  {
   System.IO.Directory.CreateDirectory(@"C:\MyDirectory");
  }


  public static void CreateDirectory2()
  {
   string directoryPath = @"c:\MyDirectory";
   System.IO.DirectoryInfo di = Directory.CreateDirectory(directoryPath);
  }


 }
}

The first method, CreateDirectory1, simply utilizes the CreateDirectory method that takes a string parameter.  In my case I passed in @"C:\MyDirectory".

The second method, CreateDirectory2, performs exactly the same action as CreateDirectory1 with the only differences being I assigned @"C:\MyDirectory" to a string variable named directoryPath and then passed this variable into the CreateDirectory method.

Now that you are armed with the basics of creating a directory, we will now move into how to check if the directory in fact exist before we attempt to create it.

Validating a Directory's Existence

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.

Moving and Deleting a Directory

Okay, by this point in time you should have a grasp on creating a directory on the server and validating a directory's existence. The next thing I want to cover is the steps available to move a directory and delete a directory.  The following code display how simple it is to move a directory. Don't forget to use the try-catch as discussed earlier.

using System;
using System.IO;


namespace SystemIO
{
 /// <summary>
 /// Summary description for article051604.
 /// </summary>
 public class article051604
 {


  static void Main(string[] args)
  {
   MoveDirectory();
  }


  public static void MoveDirectory()
  {
   string directoryPathToMove = @"c:\MyDirectory";
   string directoryPathMoveLocation = @"c:\MyDirectory1";


   Directory.Move(directoryPathToMove, directoryPathMoveLocation);
  }


 }
}

To delete a directory, just modify the MoveDirectory method to the following.

public static void DeleteDirectory()
{
 string directoryPath = @"c:\MyDirectory";
 Directory.Delete(directoryPath);
}

Finally, to delete a directory recursively, try the following. By adding the Boolean value true, the Delete method will delete subdirectories and files within the provided path.

public static void DeleteEntireDirectory()
{
 string directoryPath = @"c:\MyDirectory";
 Directory.Delete(directoryPath, true);
}

So to summarize you have been provided the necessary basics for creating a directory, moving a directory, and deleting a directory. In the near future I will provide an article to expand on System.IO, such as creating and appending to flat files. One example that may pique your interest is writing to an event log.

Good luck and take the time to play around with the System.IO namespace but by all means be careful with what you attempt to do--as always, be sure you have a current backup of the data you will be working with.

If you do not have access to a local copy of the MSDN Library, you can find all
the information you need for the System.IO namespace at the link below.

System.IO Namespace



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-29 5:56:23 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search