Loading, please wait...

A to Z Full Forms and Acronyms

Directory Handling in C#

Jun 24, 2021 c#, 2557 Views
In this article, we are going to see Directory handling in c#. In this article we are going to see all the operation which we can perform in directory. I hope you get some help from this article.

Directory Handling in C#

Introduction

In this article, we are going to see Directory handling in c#. In this article we are going to see all the operation which we can perform in directory. I hope you get some help from this article.

We are going to perform operation on directory and retrieve some information. C# provider a class called Directory which used to perform operation and get information about particular directory. Directory class has all the method as a static so you can call method by its class. There is no need to create object of Directory.

In this article we cover following topics

  • Check Directory Exist
  • Create Directory
  • Delete Directory
  • Get Creating Time
  • Get Last Access Time
  • Get Last Write Time
  • Move Directory
  • Get Parent Directory Info
  • Get List of Sub Directories
  • Get List of Files In Directory

Check Directory Exist

When we working on some project where we need to create directory dynamically but what happened when directory is already exist with that name then it will throw an error which is not good for developer. For solution of this C#’s Directory class provide a static method called Exists for checking directory is exist or not. This method take one parameter which is directory path. If directory exist then it will return true otherwise it return false.

//check directory exist
string directoryExistPath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
if (Directory.Exists(directoryExistPath))
{
    Console.WriteLine("Directory exist");
}
else
{
    Console.WriteLine("Directory not exist");
}
C#

Create Directory

For creating directory you can call Create method. This method take path as a parameter. If you want to create XYZ folder in Desktop then you need to pass path with XYX name. If you pass path like c:/abc/xyz for creating xyz folder but there is no abc folder in c drive then it will throw error.

If your directory is already exists in that place then also it will throw an error. For get rid of this you must check directory is exists or not before create any directory.

string createDirectoryPath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
if (Directory.Exists(createDirectoryPath))
{
    Console.WriteLine("Directory already exist at " + createDirectoryPath);
}
else
{
    Directory.CreateDirectory(createDirectoryPath);
    Console.WriteLine("Directory created at " + createDirectoryPath);
}
C#

Delete Directory

For delete directory you need to call Delete method of Directory. This method take one parameter which is directory path. If directory not exist on that path. It will throw an error.

//delete directory
string deleteDirectoryPath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
if (Directory.Exists(deleteDirectoryPath))
{
    Directory.Delete(deleteDirectoryPath);
    Console.WriteLine("Directory deleted at " + createDirectoryPath);
}
else
{
    Console.WriteLine("Directory not found at " + createDirectoryPath);
}
C#

If your directory is not empty means there is some other directory or files in your directory then it will also throw an error. For that there is other overloaded method which take two parameter first is directory path and second Boolean flag where you need to pass true. If you pass false and there is some child of that folder it will also throw an error.

//delete directory
string deleteDirectoryWithChildPath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
if (Directory.Exists(deleteDirectoryWithChildPath))
{
    Directory.Delete(deleteDirectoryWithChildPath, true);
    Console.WriteLine("Directory deleted at " + deleteDirectoryWithChildPath);
}
else
{
    Console.WriteLine("Directory not found at " + deleteDirectoryWithChildPath);
}
C#

 

 

Get Creating Time 

You can get the date and time when that particular directory was created using GetCreationTime method. This method also take directory pass and a parameter and return DateTime.

//get creation time
string creationTimePath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
DateTime creationTime = Directory.GetCreationTime(creationTimePath);
Console.WriteLine("Directory created at " + creationTime.ToString("MM/dd/yyyy hh:mm tt"));
C#

 

Get Last Access Time

You can also get the date and time when user access that directory using GetLastAcceesTime method. This method also take directory path as a parameter and return date time.

//get last access time
string lastAccessTimePath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
DateTime lastAccessTime = Directory.GetLastAccessTime(lastAccessTimePath);
Console.WriteLine("Directory last accessed at " + lastAccessTime.ToString("MM/dd/yyyy hh:mm tt"));
C#

 

Get Last Write Time

You can get date and time when any operation like create directory or file or any other write operation in that particular or child directory. Using GetLastWriteTime method you can get last write time. This method take directory path as a parameter.

//get last write time
string lastWriteTimePath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
DateTime lastWriteTime = Directory.GetLastWriteTime(lastWriteTimePath);
Console.WriteLine("Directory last write at " + lastWriteTime.ToString("MM/dd/yyyy hh:mm tt"));
C#

Move Directory

Here move directory means move all the child directories and files in other folder. Using Move method of Directory you can move all the child in new place. This method takes two parameter one is source path and second is destination path. If destination and source path not found or not exist then it will throw an error.

//move directory
//move its all child to new location
string mainDirectoryPath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
string pathToMove = @"C:\Users\Yogeshkumar Hadiya\Desktop\Move";
Directory.Move(mainDirectoryPath, pathToMove);
Console.WriteLine("Directory moved successfully");
C#

In above example all the files from DirectoryHandling folder will be moved on Move folder.

 

Get Parent Directory Info

Using GetParent method you can get parent directory info. This method also take directory path as a parameter. This method return DirectoryInfo which contain parent directory name, path etc.  

//get parent directory
string parentDirectoryPath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
DirectoryInfo parentDirectory = Directory.GetParent(parentDirectoryPath);
Console.WriteLine("Parent Directory Path : " + parentDirectory.FullName);
Console.WriteLine("Parent Directory Name : " + parentDirectory.Name);
C#

 

Get List of Sub Directories

Using GetDirectories method you can get list of all sub directories of you directory. This will return full path of all directories in string array. You can iterate using loops. This method take one parameter directory path.

//get sub all directories
//return paths
string subDirectoryPath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
string[] subDirectories = Directory.GetDirectories(subDirectoryPath);
if (subDirectories.Length > 0)
{
    Console.WriteLine("Directories List");
    Console.WriteLine("______________________________________________");
    foreach (var item in subDirectories)
    {
        Console.WriteLine(item);
    }
}
else
{
    Console.WriteLine("No sub directory available in this directory.");
}
C#

You can also perfume search using overloaded method of GetDirectories. This method takes two parameter directory path and search term in this case name of directory.  This search term is case sensitive and need to match whole name of directory.

//get sub all directories with search
//return paths
string subDirectorySearchPath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
string[] subDSearchirectories = Directory.GetDirectories(subDirectorySearchPath, "Child 2");
if (subDSearchirectories.Length > 0)
{
    Console.WriteLine("Directories List");
    Console.WriteLine("______________________________________________");
    foreach (var item in subDSearchirectories)
    {
        Console.WriteLine(item);
    }
}
else
{
    Console.WriteLine("No sub directory available in this directory.");
}
C#

 

Get List of Files In Directory

Using GetFiles method you can get all the files in that particular folder. This method take directory path as an parameter and return full path of files in array of string.

//get sub files
//return paths
string subFilesPath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
string[] subFiles= Directory.GetFiles(subFilesPath);
if (subFiles.Length > 0)
{
    Console.WriteLine("Files List");
    Console.WriteLine("______________________________________________");
    foreach (var item in subFiles)
    {
        Console.WriteLine(item);
    }
}
else
{
    Console.WriteLine("No sub files available in this directory.");
}
C#

You can also perfume search using overloaded method of GetFiles. This method takes two parameter directory path and search term in this case name of directory.  This search term is case sensitive and need to match whole name of file with extension.

//get sub files with search
//return paths
string subFilesSearchPath = @"C:\Users\Yogeshkumar Hadiya\Desktop\DirectoryHandling";
string[] subSearchFiles = Directory.GetFiles(subFilesSearchPath,"File 1.txt");
if (subSearchFiles.Length > 0)
{
    Console.WriteLine("Files List");
    Console.WriteLine("______________________________________________");
    foreach (var item in subSearchFiles)
    {
        Console.WriteLine(item);
    }
}
else
{
    Console.WriteLine("No sub files available in this directory.");
}
C#

 

Conclusion

I hope you get some help from this article. If yes then please share with your friend. Thank You. 

A to Z Full Forms and Acronyms