C# - Directory and DirectoryInfo Classes

In C#, the Directory and DirectoryInfo classes are tools that help you work with folders on your computer. They let you do things like creating new folders, checking if a folder exists, and finding out information about a folder, such as its name or when it was last modified. These classes are part of the System.IO toolbox, which is like a collection of tools for handling files and folders in C#.

1. 'Directory' Class:

The Directory class is a static class, which means you don't need to create an instance of it to use its methods. It provides a set of static methods to perform various directory-related operations.

  1. Directory.CreateDirectory(string path): Creates a new directory at the specified path.
  2. Directory.Delete(string path): Deletes an empty directory at the specified path.
  3. Directory.Delete(string path, bool recursive): Deletes a directory and its contents recursively if recursive is set to true.
  4. Directory.Exists(string path): Checks if a directory exists at the specified path.
  5. Directory.GetDirectories(string path): Returns an array of directory names within the specified directory.
  6. Directory.GetFiles(string path): Returns an array of file names within the specified directory.
  7. Directory.GetCreationTime(string path): Returns the creation date and time of the directory at the specified path.
  8. Directory.GetLastWriteTime(string path): Returns the last write date and time of the directory at the specified path.
  9. Directory.GetLastAccessTime(string path): Returns the last access date and time of the directory at the specified path.
  10. ... and more.

Here's an example of using the Directory class to create a directory:


using System.IO;

string path = @"C:\MyFolder\NewDirectory";
Directory.CreateDirectory(path);

2. 'DirectoryInfo' Class:

The DirectoryInfo class is like a model or a way to talk about a specific folder or directory. It allows you to work with directories through instance methods and properties. Unlike the Directory class, you need to create an instance of DirectoryInfo to use its methods.

  1. DirectoryInfo(string path): Creates a new DirectoryInfo instance representing the directory at the specified path.
  2. Create(): Creates the directory represented by the DirectoryInfo object.
  3. Delete(): Deletes an empty directory represented by the DirectoryInfo object.
  4. Delete(bool recursive): Deletes the directory and its contents recursively if recursive is set to true.
  5. Exists: Tells you if the folder or directory exists.
  6. GetDirectories(): Returns an array of DirectoryInfo objects that represent the subdirectories within the directory.
  7. GetFiles(): Returns an array of 'FileInfo' objects that represent the files within the directory.
  8. CreationTime', 'LastWriteTime', 'LastAccessTime: Properties to get or set the creation, last write, and last access times of the directory.
  9. ... and more.

Here's an example of using the DirectoryInfo class to create a directory:


using System.IO;

string path = @"C:\MyFolder\NewDirectory";
DirectoryInfo directoryInfo = new DirectoryInfo(path);
directoryInfo.Create();

Both classes provide similar functionalities, but the choice between using Directory or DirectoryInfo depends on your coding style and preference. The DirectoryInfo class is more object-oriented and allows you to access directory properties directly without calling static methods. On the other hand, the Directory class is more static and provides direct access to common directory operations without creating an instance.

3. Creating, deleting, and enumerating directories

In C#, you can create, delete, and enumerate directories using the Directory class from the System.IO namespace. This static class provides various methods for performing directory-related operations. Let's see how to use these methods:

3.1 Creating a Directory:

If you want to make a new folder or create a new directory, you can use the Directory.CreateDirectory() method. This method takes the full path of the directory you want to create as a parameter.


using System.IO;

string path = @"C:\MyFolder\NewDirectory";
Directory.CreateDirectory(path);

If the directory already exists at the specified path, the method will not raise an exception. Instead, it will do nothing and return normally.

3.2 Deleting a Directory:

To delete a directory, you can use the Directory.Delete() method. This method deletes an empty directory at the specified path. If you want to delete a directory along with all its subdirectories and files, you can use the recursive parameter set to true.


using System.IO;

string path = @"C:\MyFolder\DirectoryToDelete";
Directory.Delete(path); // Deletes an empty directory

string pathToDeleteWithContents = @"C:\MyFolder\DirectoryToDeleteWithContents";
Directory.Delete(pathToDeleteWithContents, recursive: true); // Deletes the directory along with its contents

Please exercise caution when using the 'Delete' method with the recursive parameter set to true, as it will permanently delete all the contents of the directory and its subdirectories.

3.3 Enumerating Directories:

To list all directories within a specific directory, you can use the 'Directory.GetDirectories()' method. This method returns an array of directory names as strings.


using System.IO;

string path = @"C:\MyFolder";
string[] directories = Directory.GetDirectories(path);

foreach (string directory in directories)
{
    Console.WriteLine(directory);
}

The GetDirectories method will only list the directories within the specified path. If you want to list the files within a directory, you can use the Directory.GetFiles() method, which works in a similar way.


using System.IO;

string path = @"C:\MyFolder";
string[] files = Directory.GetFiles(path);

foreach (string file in files)
{
    Console.WriteLine(file);
}

These are the basic operations for creating, deleting, and enumerating directories in C#. Make sure to handle exceptions properly, especially when dealing with I/O operations, to ensure that your application behaves as expected.

4. Moving and renaming directories

In C#, you can move and rename directories using the Directory class or the DirectoryInfo class from the 'System.IO' namespace. Both approaches provide similar functionality, but the DirectoryInfo class allows for more object-oriented and flexible operations. Let's explore how to move and rename directories using both methods:

4.1 Moving a Directory:

To move a directory (i.e., cut and paste it to a new location), you can use the 'Directory.Move()' method or the 'DirectoryInfo.MoveTo()' method.

Using Directory.Move():


using System.IO;

string sourcePath = @"C:\MyFolder\SourceDirectory";
string destinationPath = @"D:\NewFolder\DestinationDirectory";

Directory.Move(sourcePath, destinationPath);

Using DirectoryInfo.MoveTo():


using System.IO;

string sourcePath = @"C:\MyFolder\SourceDirectory";
string destinationPath = @"D:\NewFolder\DestinationDirectory";

DirectoryInfo sourceDirectory = new DirectoryInfo(sourcePath);
sourceDirectory.MoveTo(destinationPath);

Both methods achieve the same result: the directory at sourcePath is moved to destinationPath.

4.2 Renaming a Directory:

To rename a directory, you can use the 'Directory.Move()' method or the 'DirectoryInfo.MoveTo()' method, just like in the moving example. The only difference is that in the renaming scenario, the new destination path will have the new name for the directory.

Using Directory.Move() to rename:


using System.IO;

string oldNamePath = @"C:\MyFolder\OldDirectoryName";
string newNamePath = @"C:\MyFolder\NewDirectoryName";

Directory.Move(oldNamePath, newNamePath);

Using DirectoryInfo.MoveTo() to rename:


using System.IO;

string oldNamePath = @"C:\MyFolder\OldDirectoryName";
string newNamePath = @"C:\MyFolder\NewDirectoryName";

DirectoryInfo directoryInfo = new DirectoryInfo(oldNamePath);
directoryInfo.MoveTo(newNamePath);

Both methods will rename the directory located at oldNamePath to newNamePath.

As mentioned earlier, the DirectoryInfo approach allows for a more object-oriented approach, which can be useful when you need to perform multiple operations on the same directory. It also provides access to additional properties and methods related to the directory, such as its creation time or its subdirectories and files. On the other hand, the Directory class provides static methods and is more suitable for one-off operations where you don't need to maintain an object reference.

Select the method that suits how you like to write code and what you need. Make sure to deal with any problems the right way so that when you move or rename directories, everything goes smoothly without any errors.

5. Accessing directory information and properties

In C#, you can get details about directory, can access directory information and properties using the Directory class or the DirectoryInfo class from the System.IO namespace. Both approaches allow you to retrieve various details about a directory, such as its creation time, last write time, subdirectories, and files. Let's explore how to access directory information and properties using both methods:

5.1 Accessing 'Directory' Information using the 'Directory' class:
Using the Directory class, you can use static methods to access directory information.

•Get the creation time of a directory:


using System.IO;

string path = @"C:\MyFolder\MyDirectory";
DateTime creationTime = Directory.GetCreationTime(path);
Console.WriteLine($"Creation Time: {creationTime}");

•Get the last write time of a directory:


using System.IO;

string path = @"C:\MyFolder\MyDirectory";
DateTime lastWriteTime = Directory.GetLastWriteTime(path);
Console.WriteLine($"Last Write Time: {lastWriteTime}");

•Get the last access time of a directory:


using System.IO;

string path = @"C:\MyFolder\MyDirectory";
DateTime lastAccessTime = Directory.GetLastAccessTime(path);
Console.WriteLine($"Last Access Time: {lastAccessTime}");
5.2 Accessing 'Directory' Properties using the 'DirectoryInfo' class:

Using the DirectoryInfo class, you create an instance of the directory and then access its properties directly.

•Get the creation time of a directory using DirectoryInfo:


using System.IO;

string path = @"C:\MyFolder\MyDirectory";
DirectoryInfo directoryInfo = new DirectoryInfo(path);
DateTime creationTime = directoryInfo.CreationTime;
Console.WriteLine($"Creation Time: {creationTime}");

•Get the last write time of a directory using DirectoryInfo:


using System.IO;

string path = @"C:\MyFolder\MyDirectory";
DirectoryInfo directoryInfo = new DirectoryInfo(path);
DateTime lastWriteTime = directoryInfo.LastWriteTime;
Console.WriteLine($"Last Write Time: {lastWriteTime}");

•Get the last access time of a directory using DirectoryInfo:


using System.IO;

string path = @"C:\MyFolder\MyDirectory";
DirectoryInfo directoryInfo = new DirectoryInfo(path);
DateTime lastAccessTime = directoryInfo.LastAccessTime;
Console.WriteLine($"Last Access Time: {lastAccessTime}");
5.3 Accessing Subdirectories and Files using the 'DirectoryInfo' class:

The DirectoryInfo class also provides methods to access subdirectories and files within a directory.

•Get an array of subdirectories using DirectoryInfo:


using System.IO;

string path = @"C:\MyFolder";
DirectoryInfo directoryInfo = new DirectoryInfo(path);
DirectoryInfo[] subdirectories = directoryInfo.GetDirectories();

foreach (DirectoryInfo subdirectory in subdirectories)
{
    Console.WriteLine(subdirectory.FullName);
}

•Get an array of files using DirectoryInfo:


using System.IO;

string path = @"C:\MyFolder";
DirectoryInfo directoryInfo = new DirectoryInfo(path);
FileInfo[] files = directoryInfo.GetFiles();

foreach (FileInfo file in files)
{
    Console.WriteLine(file.FullName);
}

Both the Directory class and the DirectoryInfo class provide convenient ways to access directory information and properties. The DirectoryInfo class allows for more object-oriented operations, which can be useful when you need to perform multiple operations on the same directory or when you want to access other properties and methods related to the directory.