Working With DirectoryInfo In C#

Introduction

 
C# DirectoryInfo class provides functionality to work with folders or directories. This article will explain the DirectoryInfo class and its usage with C# code examples. The DirectoryInfo class is declared in the System.IO namespace that must be imported before you can use this class.
 

C# DirectoryInfo Class

 
The DirectoryInfo class shares almost all of the same properties as the FileInfo class, except that they operate on directories not files. The DirectoryInfo class does not have static methods and can only be used on instantiated objects. The DirectoryInfo object represents a physical directory on a disk. It also provides instance methods for deleting folders, creating a new directory and sub directories.
 
When to use C# DirectoryInfo class
 
If you are going to reuse an object several times, consider using the instance method of DirectoryInfo instead of the corresponding static methods of the Directory class.
 
Some of the most useful methods of the DirectoryInfo class are:
 
S.No Methods Description
1 Create This method is used to create the new directory.
2 CreateSubdirectory This method is used to create a subdirectory or subdirectories on the specified path.
3 MoveTo Moves a DirectoryInfo instance and its contents to a new path.
4 Delete Deletes this instance of a DirectoryInfo, specifying whether to delete subdirectories and files.
5 GetDirectories This method is used to get the sub directories in the given directory path.
6 GetFiles The GetFiles method is used to get the files in the specified folder.
 
Figure1 DirectoryInfo Methods
 
Now Let us see the some of the methods in the DirectoryInfo class.
 

Create a new directory in C#

 
The Create method is used to create the new directory. 
  1. static void Main(string[] args)  
  2. {  
  3.     String path = @"D:\MyTestFile1.txt";  
  4.     DirectoryInfo fl = new DirectoryInfo(path);  
  5.        fl.Create();  
  6.        {  
  7.           Console.WriteLine("Directory has been created");  
  8.        }  
  9. }  

Create SubDirectory in C#

 
The CreateSubdirectory method is used to create a subdirectory or subdirectories on the specified path.
  1. static void Main(string[] args)  
  2. {  
  3.             String path = @"D:\MyTestFile1.txt";  
  4.             DirectoryInfo fl = new DirectoryInfo(path);  
  5.             DirectoryInfo dis = fl.CreateSubdirectory("hellotest");  
  6.             {  
  7.             Console.WriteLine("Directory has been created");  
  8.             }  
  9. }  

Move a directory in C#

 
The MoveTo method of moves a directory to a new location including tts contents.
  1. static void Main(string[] args)  
  2. {  
  3.             String path = @"D:\MyTestFile1.txt";  
  4.             string path1 = @"D:\NewFile1.txt";  
  5.             DirectoryInfo f1 = new DirectoryInfo(path);  
  6.             DirectoryInfo f2 = new DirectoryInfo(path1);  
  7.             f1.MoveTo(path1);  
  8.             {  
  9.             Console.WriteLine("Directory has been Moved");  
  10.             }  
  11. }
 

Delete a directory in C#

 
The Delete method deletes a directory, specifying whether to delete subdirectories and files.
  1. static void Main(string[] args) {  
  2.  string path = @ "D:\NewFile1.txt";  
  3.  DirectoryInfo f1 = new DirectoryInfo(path);  
  4.  f1.Delete(); {  
  5.   Console.WriteLine("Directory has been deleted");  
  6.  }  
  7. }  

Get Subdirectories of a directory in C# 

 
GetDirectories method is used to get sub directories in the given directory path, or returns the subdirectories of the current directory.
  1. static void Main(string[] args) {  
  2.   try {  
  3.    DirectoryInfo di = new DirectoryInfo(@ "D:\newFile\");  
  4.     DirectoryInfo[] dir1 = di.GetDirectories();   
  5.     Console.WriteLine("The number of directories containing is {0}.", dir1.Length);  
  6.    }  
  7.    catch (Exception e) {  
  8.     Console.WriteLine("The process failed: {0}", e.ToString());  
  9.    }  
  10.   }  

Get all files in a folder in C#

 
The GetFiles method is used to get the files in the specified folder. The following code loops through all directories and gets sub directories and loops through them to get all files.
  1. static void Main(string[] args)      
  2. {  
  3.     DirectoryInfo di = new DirectoryInfo(@"D:\newfile");  
  4.     DirectoryInfo[] dirs = di.GetDirectories();  
  5.     foreach (DirectoryInfo diNext in dirs)  
  6.     {  
  7.         Console.WriteLine("The number of files in {0} is {1}", diNext, diNext.GetFiles().Length);  
  8.     }  
  9. }  
Here is a complete example. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.IO;  
  6.     
  7. namespace Createdirectory  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13. // Create Method  
  14.             String path = @"D:\MyTestFile1.txt";  
  15.             DirectoryInfo fl = new DirectoryInfo(path);  
  16.             fl.Create();  
  17.             {  
  18.                 Console.WriteLine("Directory has been created");  
  19.             }  
  20.     
  21. // CreateSubdirectory Method  
  22.             String path = @"D:\MyTestFile1.txt";  
  23.             DirectoryInfo fl = new DirectoryInfo(path);  
  24.             DirectoryInfo dis = fl.CreateSubdirectory("hellotest");  
  25.             {  
  26.                 Console.WriteLine("Directory has been created");  
  27.             }  
  28. // MoveTo Method  
  29.             String path = @"D:\MyTestFile1.txt";  
  30.             string path1 = @"D:\NewFile1.txt";  
  31.             DirectoryInfo f1 = new DirectoryInfo(path);  
  32.             DirectoryInfo f2 = new DirectoryInfo(path1);  
  33.             f1.MoveTo(path1);  
  34.             {  
  35.                   Console.WriteLine("Directory has been Moved");  
  36.             }  
  37.     
  38. // Delete Method  
  39.             string path = @"D:\NewFile1.txt";  
  40.             DirectoryInfo f1 = new DirectoryInfo(path);  
  41.             f1.Delete();  
  42.             {  
  43.                 Console.WriteLine("Directory has been deleted");  
  44.             }  
  45.     
  46. // GetDirectories method  
  47.             try  
  48.             {  
  49.                 DirectoryInfo di = new DirectoryInfo(@"D:\newFile\");  
  50.                 DirectoryInfo[] dir1 = di.GetDirectories();  
  51.                 Console.WriteLine("The number of directories containing is {0}.", dir1.Length);  
  52.             }  
  53.             catch (Exception e)  
  54.             {  
  55.                 Console.WriteLine("The process failed: {0}", e.ToString());  
  56.             }  
  57.     
  58. // GetFiles method  
  59.             DirectoryInfo di = new DirectoryInfo(@"D:\newfile");  
  60.             DirectoryInfo[] dirs = di.GetDirectories();  
  61.             foreach (DirectoryInfo diNext in dirs)  
  62.             {  
  63.                 Console.WriteLine("The number of files in {0} is {1}", diNext,      
  64.                 diNext.GetFiles().Length);  
  65.             }  
  66.         }  
  67.     }  
  68. }  
The DirectoryInfo class provides the following properties that enable you to retrieve information about a directory.
 
S.No Property Description
1 CreationTime This property returns the creation of the directory date and time.
2 Exists It returns whether the directory exists or not as Boolean result.
3 FullName It returns the full name of the file from the root directory.
4 Name It returns the name of the directory
5 LastAccessTime It returns the date and time of the last access time
6 LastWriteTime It returns the last file saving date and time
7 Root Gets the root portion of a path.
 
Figure 2  DirectoryInfo Properties
 
DirectoryInfo Properties example. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.IO;  
  6. namespace directoryinfoproperty {  
  7.  class Program {  
  8.   static void Main(string[] args) {  
  9.    DirectoryInfo fi = new DirectoryInfo(@ "D:\newfile");  
  10.    Console.WriteLine("Directory name is {0} ", fi.Name);  
  11.    Console.WriteLine("Directory creation time is {0} ", fi.CreationTime.ToLongTimeString());  
  12.    Console.WriteLine("Directory Lastaccesstime is {0} ", fi.LastAccessTime.ToLongDateString());  
  13.    Console.WriteLine("Directory exist is: ", fi.Exists);  
  14.    Console.WriteLine("Directory LastWriteTime is {0} ", fi.LastWriteTime);  
  15.    Console.WriteLine("Directory root is {0} ", fi.Root);  
  16.   }  
  17.  }  
  18. }  

Conclusion

 
C# DirectoryInfo class is very useful for working with directories. In this article and code samples, we learned how to use various properties and methods of DirectoryInfo to work with directories in C#.
 


Similar Articles