Directory class
Directory class
System.IO.Directory class in the .NET Framework class library provides static methods
for creating, copying, moving, and deleting directories and subdirectories. Before you
can use the Directory class, you must import the System.IO namespace.
1. using System.IO;
Create a Folder in C#
Directory.CreateDirectory method creates a directory or folder in the specified path with
the specified Windows security. You can also create a directory on a remote computer.
The following code snippet creates a Temp folder in C:\ drive if the directory does not
exists already. Assuming the account running the code has admin permissions.
Directory.CreateDirectory is also creates a sub directory or sub folder. All you have to
do is to specify the path of the folder in which this subdirectory will be created in. The
following code snippet creates 'Mahesh' subdirectory in C:\Temp directory.
Delete a folder in C#
Directory.Delete method deletes an empty folder from the specified path permanently. If
a folder has sub folders and/or files, you must delete them before you can delete a
folder. If you try to delete a file that is not empty, you will get an error message.
The following code snippet checks if a directory has subdirectories and files and delete
them before deleting a directory.
Move a folder in C#
Directory.Move method moves an existing directory to a new specified directory with full
path. The Move method takes two parameters. The Move method deletes the original
directory.
The following code snippet moves the source directory to the destination directory.
Copy a folder in C#
There is no method to copy a directory. The copying a directory is a process of creating
a new directory that you to want a directory to move to and then copying subdirectory
and files.
Get and Set Directory Creation Time
The SetCreationTime and GetCreationTime methods are used to set and get the
creation date and time of the specified file. The following code snippet sets and gets the
creation time of a file.
Enumerate Directory in C#
The Directory.EnumerateDirectories method returns an enumerable collection of
directory names in the specified directory.
Enumerate Files in C#
The Directory.EnumerateFiles method returns an enumerable collection of file names in
the specified directory.