DirectoryInfo Class in C#
In C#, the System.IO namespace has the DirectoryInfo class, which offers a method for interacting with file system directories (folders). It is utilized to get directory-related data, manage directory attributes, and conduct operations on directories.
- The DirectoryInfo class is utilized for file and directory management activities and is a component of the larger.NET Framework and.NET Core libraries.
Properties of DirectoryInfo Class in C#
You may obtain information about a directory (or folder) in the file system with the DirectoryInfo class in the C# language. Here are a few of the DirectoryInfo class's frequently used properties
Properties | Description |
FullName | Returns the Directory's complete path, which includes its name. |
Name | Retrieves the Directory's name only, not its path. |
Parent | Gets the current Directory's parent directory using the parent keyword. |
Exists | This value describes whether the Directory is present in the file system. |
Attribute | Gets or modifies the characteristics connected to the Directory. This feature lets you change attributes like read-only, hidden, and more. |
Root | Returns the directory path's root segment. |
extension | Gets the associated with the Directory's name. The return value of this field is an empty string because directories don't have extensions. |
GetFileSystemInfos() | The method provides an array of FileSystemInfo objects that represent the files and directories in the current Directory. |
Methods:
The DirectoryInfo class in C# offers several crucial methods for interacting with file system directories. As always, while working with file system operations, handle exceptions properly.
Methods | Description |
create | The DirectoryInfo object's representation of a directory is created using the method. Calling this method with an existing directory has no effect. |
Delete | The Directory is deleted using the method. You can decide whether to destroy everything (including all subdirectories and files) using the optional recursive parameter. |
GetFiles | An array of FileInfo objects representing the files in the Directory are returned by the GetFiles() function. You can offer optional file-filtering choices and search patterns. |
GetDirectories | A list of DirectoryInfo objects representing the subdirectories in the Directory is returned by the GetDirectories() function. Search patterns and choices to filter the subdirectories are optional. |
MoveTo() | The Directory can be relocated using the MoveTo() method. The new route is offered as support. An exception is thrown if the target directory already exists. |
EnumerateFiles() and EnumerateDirectories(), | These methods return enumerators that let you cycle through files and directories slowly. These methods may be more memory-efficient when dealing with huge directory structures than GetFiles() and GetDirectories(). |
Example:
We are constructing a T&E directory in the example below by specifying the directory path.
using System;
using System.IO;
namespace DirectoryCreationExample
{
class Program1
{
static void Main(string[] args)
{
string directoryPath = @"C:\MyDirectory"; // Provide the desired directory path here
try
{
// Create a DirectoryInfo object
DirectoryInfo directory = new DirectoryInfo(directory path);
// Check if the Directory already exists
if (Directory. Exists)
{
Console.WriteLine("Directory already exists.");
return;
}
// Create the Directory
directory.Create();
Console.WriteLine("The directory has been created successfully.");
}
Catch (Exception e)
{
Console.WriteLine("Directory not created: " + e.Message);
}
}
}
}
Output:
![DirectoryInfo Class in C#](https://static.tutorialandexample.com/csharp/directory-info-class-in-csharp1.png)
- Making a DirectoryInfo Object Using the given directory path, a DirectoryInfo object with the name directory is made inside the try block.
- The program uses the Exists attribute of the DirectoryInfo object to determine whether the Directory already exists.
- The program terminates if the Directory is present and a notice is displayed.
- The program invokes the Create method on the DirectoryInfo object to create the Directory if it does not already exist.
Following a directory creation attempt, the program prints the necessary messages to the console indicating whether the Directory was successfully formed.
Example:
The program shows how to delete a directory using the DirectoryInfo class.
using System;
using System.IO;
namespace DirectoryDeletionExample
{
class Program2
{
static void Main(string[] args)
{
string directoryPath = @"C:\T&E"; // Provide the directory path to delete
try
{
// Create a DirectoryInfo object
DirectoryInfo directory = new DirectoryInfo(directory path);
// Delete the Directory
directory.Delete();
Console.WriteLine("The directory has been deleted successfully.");
}
Catch (Exception e)
{
Console.WriteLine("Something went wrong: " + e.Message);
}
}
}
}
Output:
![DirectoryInfo Class in C#](https://static.tutorialandexample.com/csharp/directory-info-class-in-csharp2.png)
To deal with any unexpected errors that may occur. Ensure you're running the program in a situation where you can remove directories from the path supplied.
- Making a DirectoryInfo Object Using the given directory path, a DirectoryInfo object with the name directory is made inside the try block.
- The program invokes the destroy method on the DirectoryInfo object to destroy the Directory.
- Output following a directory deletion attempt, the program sends the proper messages to the console informing the user if the Directory was successfully deleted or if an exception occurred.
Example:
A directory can be moved from one place to another using the DirectoryMethod.
using System;
using System.IO;
class Program3
{
static void Main(string[] args)
{
string sourceDirectory = @"C:\Myfile";
string destinationDirectory = @"C:\Therefile";
try
{
Directory.Move(sourceDirectory, destinationDirectory);
Console.WriteLine("Directory moved successfully.");
}
Catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
}
}
Output:
![DirectoryInfo Class in C#](https://static.tutorialandexample.com/csharp/directory-info-class-in-csharp3.png)
The two required parameters are the source and destination directory paths. The Directory is the move method. You can move a directory from one place to another using the Move method.
- The two required parameters are the source and destination directory path
- It would be best to replace DestinationDirectory with the path to the final destination andSourceDirectory with the path to the Directory you wish to relocate.
- The program will attempt to relocate the Directory and display the necessary notifications indicating whether the move was successful or had any problems.
- Verify that you have the right permissions to operate on directories in the designated places.
Example:
The DirectoryInfo class from the System.IO namespace can retrieve directory details in C#.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string directoryPath = @"C:\MyFile"; // Provide the directory path
try
{
// Create a DirectoryInfo object
DirectoryInfo directory info = new DirectoryInfo(directory path);
// Check if the Directory exists
if (directory info. Exists)
{
Console.WriteLine("Directory Name: " + directoryInfo.Name);
Console.WriteLine(“Full Path:” + directoryInfo.FullName);
Console.WriteLine("Creation Time: " + directoryInfo.CreationTime);
Console.WriteLine("Last Access Time: " + directoryInfo.LastAccessTime);
Console.WriteLine("Last Write Time: " + directoryInfo.LastWriteTime);
Console.WriteLine("Attributes:" + directoryInfo.Attributes);
Console.WriteLine("Parent Directory: " + directoryInfo.Parent);
Console.WriteLine("Root Directory: " + directoryInfo.Root);
}
else
{
Console.WriteLine("Directory does not exist.");
}
}
Catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
}
}
Output:
![DirectoryInfo Class in C#](https://static.tutorialandexample.com/csharp/directory-info-class-in-csharp4.png)
- This class offers several attributes and methods to get data from a file system directory (folder).
- The path to the Directory you want to receive details should be substituted for C: Directory.
- To show various information about the Directory, like its name, full path, creation time, and other facts, the program will create a DirectoryInfo object and utilize its properties.
To access the provided Directory, ensure the program runs with the correct permissions. To deal with potential issues while accessing the file system, adequate exception handling is also advised.
Example:
A subdirectory can be created inside an existing directory represented by a DirectoryInfo object using the CreateSubdirectory function of the DirectoryInfo class.
using System;
using System.IO;
class Program4
{
static void Main(string[] args)
{
string parentDirectory = @"C:\ParentDirectory"; // Provide the parent directory path
string subdirectoryName = "SubDirectory"; // Specify the subdirectory name
try
{
DirectoryInfo parentInfo = new DirectoryInfo(parentDirectory);
DirectoryInfo subdirectoryInfo = parentInfo.CreateSubdirectory(subdirectoryName);
Console.WriteLine("Subdirectory created successfully at: " + subdirectoryInfo.FullName);
}
Catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
}
}
Output:
![DirectoryInfo Class in C#](https://static.tutorialandexample.com/csharp/directory-info-class-in-csharp5.png)
- In C#, you can use the Directory. The createDirectory or the CreateSubdirectory method of the DirectoryInfo class creates a subfolder inside an existing directory.
- The Directory's CreateDirectory method. You can create a subdirectory inside an existing directory using the CreateDirectory function.
- It accepts as an argument the path to the new subfolder.
Example:
A Sample program retrieves and displays a specified directory's subdirectories using the GetDirectories function from the DirectoryInfo class.
using System;
using System.IO;
class Program5
{
static void Main(string[] args)
{
string parentDirectory = @"C:\ParentDirectory"; // Provide the parent directory path
try
{
DirectoryInfo parentInfo = new DirectoryInfo(parentDirectory);
if (parentInfo.Exists)
{
DirectoryInfo[] subdirectories = parentInfo.GetDirectories();
if (subdirectories. Length > 0)
{
Console.WriteLine("Subdirectories in " + parentInfo.FullName + ":");
for each (var subdirectory in subdirectories)
{
Console.WriteLine(subdirectory.Name);
}
}
else
{
Console.WriteLine("No subdirectories found in " + parentInfo.FullName);
}
}
else
{
Console.WriteLine("Parent directory does not exist.");
}
}
Catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
}
}
Output:
![DirectoryInfo Class in C#](https://static.tutorialandexample.com/csharp/directory-info-class-in-csharp6.png)
You can retrieve subdirectories for the directory by entering its path in the format ParentDirectory.
- Using the Exists attribute of the DirectoryInfo object, the program determines whether they parent directory is present.
- It utilizes the GetDirectories method to get a array of DirectoryInfo objects representing the subdirectories if the parent directory is present.
- The program displays a suitable noticed if no subdirectories are discovered.
Any potential exceptions are deal with properly to prevent them from happening again.