Managing Directories in .NET
page 3 of 3
by Steven Swafford
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 19145/ 34

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


View Entire Article

User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 11:02:09 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search