Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/articles/c-sharp-tutorials/)
-   -   .Net's Directory Class Overview (http://www.go4expert.com/articles/nets-directory-class-overview-t4186/)

pradeep 6May2007 23:52

.Net's Directory Class Overview
 

Class overview



Microsoft documentation says the Directory class exposes static methods for creating, moving, and enumerating through directories and subdirectories. In addition, you may access and manipulate various directory attributes such as creation or last modified time stamps, along with the Windows access control list.

An important aspect of the Directory class is that its methods are static, which means you can call them without having an instance of a Directory. Let's begin the tour of the Directory class with the basics, including creating, deleting, and moving directories.

The basics



The Directory class provides numerous static methods for working with directories. These static methods perform security checks on all methods. I'll examine most of these methods, with the first group consisting of the basics of working with directories:


  • CreateDirectory: Allows you to create new directories or subdirectories. Also, you may establish directory security with its creation.
  • Delete: Allows you to delete a specific empty directory from the system. This method throws an IOException if the directory specified in the path parameter contains files or subdirectories.
  • Exists: Allows you to determine if a specific directory exists. The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory.
  • Move: Allows you to move a file or directory to a new location. It accepts two parameters: the directory or file to move and its destination.
The C# Windows console application in Snippet A uses these methods to create, move, and delete directories. It uses the Exists method throughout the code to determine if a directory exists. All calls to the Directory class methods are enclosed in try/catch blocks. The code begins with a directory called test on the C drive. It uses the Path class to determine if the string containing the directory name has a file extension. If so, it determines it is a path to a file and not a directory and the application halts. This directory is created if it does not already exist. Next, the directory is renamed to go4expert and finally deleted.

Snippet A
Code: CSharp

using System;
  using System.Collections.Generic;
  using System.Text;
  using System.IO;
   
  namespace TRDirectory
  {
   
      class Program
      {
   
          static void Main(string[] args)
          {
   
              string testPath = "c:\\test";
   
              if (Path.HasExtension(testPath))
              {
                  Console.WriteLine("This is a file path, not a directory.");
              }
              else
              {
   
                  if (Directory.Exists(testPath))
                  {
                      Console.WriteLine("This directory already exists.");
                  }
                  else
                  {
   
                      try
                      {
                          Directory.CreateDirectory(testPath);
                      }
                      catch (IOException ex)
                      {
                          Console.WriteLine("Error creating directory {0} - {1}", testPath, ex.Message.ToString());
                      }
                  }
   
                  if (Directory.Exists(testPath))
                  {
   
                      try
                      {
                          Directory.Move(testPath, "c:\\go4expert");
                      }
                      catch (IOException ex)
                      {
                          Console.WriteLine("Error moving directory {0} - {1}", testPath, ex.Message.ToString());
                      }
                  }
   
                  if (Directory.Exists("c:\\go4expert"))
                  {
   
                      try
                      {
                          Directory.Delete("c:\\go4expert", true);
                      }
                      catch (IOException ex)
                      {
                          Console.WriteLine("Error deleting directory c:\\go4expert - {0}", ex.Message.ToString());
                      }
                  }
              }
          }
      }
  }

Directories and their contents



Once a directory is created, it is often necessary to peruse its contents or examine the directory itself. The Directory class makes it easy to access information on the directory as well as its contents via various methods and properties. These methods are outlined in the following list:
  • GetCurrentDirectory: Returns the current application's working directory.
  • GetDirectories: Returns a list of subdirectories for a specific directory as an array of string values.
  • GetDirectoryRoot: Returns the volume information, root information, or both for the specified path.
  • GetFiles: Returns a string array containing the filenames within a specific directory.
  • GetFileSystemEntries: Returns a string array containing the filenames and directories within a specific directory.
  • GetParent: Retrieves the parent directory of the specified path, including both absolute and relative paths as a string value.
  • GetLogicalDrives: Retrieves the names of the logical drives on the computer in the form <drive letter>:\ within a string array.
The C# code in Snippet B provides a sample of using these methods. Basically, it displays all information regarding the current application directory, all subdirectories and files, the root directory, and all logical drives on the current system.

Snippet B
Code: CSharp

using System;
  using System.Collections.Generic;
  using System.Text;
  using System.IO;
   
  namespace TRDirectory
  {
      class Program
      {
          static void Main(string[] args)
          {
              string curDir;
              inti;
   
              try
              {
                  curDir = Directory.GetCurrentDirectory();
                  Console.WriteLine("Current application directory: " + curDir);
                  subDirs = Directory.GetDirectories(curDir);
   
                  for (i = 0; i <= subDirs.GetUpperBound(0); i++)
                  {
                      Console.WriteLine("Subdirectory: " + subDirs[i]);
                  }
                  Console.WriteLine("Root info: " + Directory.GetDirectoryRoot(Directory.GetCurrentDirectory()));
   
                  for (i = 0; i <= Directory.GetFileSystemEntries(curDir).GetUpperBound(0); i++)
                  {
                      Console.WriteLine("System entries: " + Directory.GetFileSystemEntries(curDir)[i]);
                  }
   
                  for (i = 0; i <= Directory.GetLogicalDrives().GetUpperBound(0); i++)
                  {
                      Console.WriteLine("Logical drives: " + Directory.GetLogicalDrives()[i]);
                  }
              }
              catch (IOException e)
              {
                  Console.WriteLine("Exception {0}", e.Message.ToString());
              }
          }
      }
  }

Time and date stamps



It is often advantageous to know when a directory was created or the last time it was accessed or modified. The Directory class provides the following methods for working with time and date stamps:
  • GetCreationTime: Gets the creation date and time of a directory.
  • GetLastAccessTime: Returns the date and time of the specified file or directory that was last accessed.
  • GetLastWriteTime: Returns the date and time of the specified file or directory that was last written to.
  • SetCreationTime: Sets the creation date and time for the specified file or directory.
  • SetLastAccessTime: Sets the date and time of the specified file or directory that was last accessed.
  • SetLastWriteTime: Sets the date and time a directory was last written to.
The C# code in Snippet C provides a list of all dizgrectories on the C drive with date and times when they were last accessed, changed, and initially created. The last access time is reset to the current date and time for each directory.

Snippet C
Code: CSharp

using System;
  using System.Collections.Generic;
  using System.Text;
  using System.IO;
   
  namespace TRDirectory
  {
   
      class Program
      {
   
          static void Main(string[] args)
          {
   
              string[] subDirs;
              inti;
              DateTimedtCreated;
              DateTimedtAccessed;
              DateTimedtWrite;
   
              try
              {
                  subDirs = Directory.GetDirectories("c:\\");
   
                  for (i = 0; i <= subDirs.GetUpperBound(0); i++)
                  {
                      dtCreated = Directory.GetCreationTime(subDirs[i]);
                      dtAccessed = Directory.GetLastAccessTime(subDirs[i]);
                      dtWrite = Directory.GetLastWriteTime(subDirs[i]);
                      Console.WriteLine("Subdirectory {0}", subDirs[i]);
                      Console.WriteLine("Created: {0}", dtCreated.ToString());
                      Console.WriteLine("Last accessed: {0}", dtAccessed.ToString());
                      Console.WriteLine("Last changed: {0}", dtWrite.ToString());
                      Directory.SetLastAccessTime(subDirs[i], DateTime.Now);
                  }
              }
              catch (IOException e)
              {
                  Console.WriteLine("Exception {0}", e.Message.ToString());
              }
          }
      }
  }

Another aspect of the system



Working with files requires directory access and often manipulation. The System.IO namespace's Directory class provides everything necessary to create and manipulate directories and its contents to determine when they were created and last accessed. Furthermore, an essential aspect of an administrator's job is controlling access to system resources with directory access being just one piece.


All times are GMT +5.5. The time now is 15:39.