January 28, 2021
Hot Topics:

Accessing Files and Directories

  • By Mark Strawmyer
  • Send Email »
  • More Articles »

Working with Directories

There two classes for the manipulation of directories. The classes are named Directory and the DirectoryInfo. The Directory class provides static methods for directory manipulation. The DirectoryInfo class provides instance methods for directory manipulation. They provide the same features and functionality, so the choice comes down to whether you need an instance of an object or not. The members include, but are not limited to the following:

  • Create—create a directory
  • Delete—delete a directory
  • GetDirectories—return subdirectories of the current directory
  • MoveTo—move a directory to a new location

Sample Code to Produce a List of All Directories

The following sample code demonstrates the ability to produce a list of directories using recursion. A recursive procedure is one that calls itself. You must ensure that your procedure does not call itself indefinitely; otherwise, you'll eventually run out of memory. In this case, there are a finite number of subdirectories, so there is automatically a termination point.

using System;using System.IO;namespace CodeGuru.FileOperations{  /// <remarks>  /// Sample to demonstrate reading the contents of directories.  /// </remarks>  class ReadDirectory  {   /// <summary>   /// The main entry point for the application.   /// </summary>   [STAThread]   static void Main(string[] args)   {     DirectoryInfo dirInfo = new DirectoryInfo("c:\\");     Console.WriteLine("Root: {0}", dirInfo.Name);     ReadDirectory.ProduceListing(dirInfo, "  ");     Console.ReadLine();   }   /*    * Recursively produce a list of files    */   private static void ProduceListing(DirectoryInfo dirInfo,                                       string Spacer)   {     Console.WriteLine(Spacer + "{0}", dirInfo.Name);     foreach(DirectoryInfo subDir in dirInfo.GetDirectories())     {      Console.WriteLine(Spacer + Spacer + "{0}", subDir.Name);      if( subDir.GetDirectories().Length > 0 )      {        ProduceListing(subDir, Spacer + "  ");      }     }   }  }}

Page 2 of 3

This article was originally published on September 9, 2003

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date