Categories
Articles Technology

How to handle directories in C# .NET

Introduction

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

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

In this article, we cover the 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 are working on some project where we need to create directory dynamically but what happens when directory already exists 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 exist or not. This method takes one parameter which is the directory path. If the directory exists, then it will return true otherwise it returns false.

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

Create Directory

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

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

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

Delete Directory

To delete the directory, you need to call the Delete method of Directory. This method takes one parameter which is the directory path. If a directory does not exist on that path, it will throw an error.

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

If your directory is not empty, which means there is some other directory or files in your directory then it will also throw an error. For that, there is another overloaded method that takes two parameters, the 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\somebody\Desktop\DirectoryHandling";
if (Directory.Exists(deleteDirectoryWithChildPath)) {
    Directory.Delete(deleteDirectoryWithChildPath, true);
    Console.WriteLine("Directory deleted at " + deleteDirectoryWithChildPath);
} else {
    Console.WriteLine("Directory not found at " + deleteDirectoryWithChildPath);
}

Get Creating Time 

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

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

Get Last Access Time

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

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

Get Last Write Time

You can get date and time when any operation is performed like creating 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 takes directory path as a parameter.

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

Move Directory

Here move directory means moving all the child directories and files to another folder. Using Move method of Directory, you can move all the child elements to a new place. This method takes two parameters one is source path and second is destination path. If destination and source path are not found or do not exist, then it will throw an error.

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

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

Get Parent Directory Info

Using GetParent method you can get parent directory info. This method also takes directory path as a parameter. This method returns DirectoryInfo which contains parent directory name, path, etc.  

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

Get List of Sub Directories

Using GetDirectories method you can get a list of all subdirectories of your directory. This will return the full path of all directories in string array. You can iterate using loops. This method takes one parameter as a directory path.

//get sub all directories
//return paths
string subDirectoryPath = @ "C:\Users\somebody\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.");
}

You can also perform searches using the overloaded method of GetDirectories. This method takes two parameters, directory path and search term in this case name of directory.  This search term is case sensitive and needs to match the whole name of directory.

//get sub all directories with search
//return paths
string subDirectorySearchPath = @ "C:\Users\somebody\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.");
}

Get List of Files In Directory

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

//get sub files
//return paths
string subFilesPath = @ "C:\Users\somebody\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.");
}

You can also perform searches using the 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 needs to match the whole name of file with extension.

//get sub files with search
//return paths
string subFilesSearchPath = @ "C:\Users\somebody\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.");
}

Conclusion

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

source: c-sharpcorner .