HomeC# A Look at C# Directory and DirectoryInfo C...
A Look at C# Directory and DirectoryInfo Classes
Have you ever tried to understand the organization and interaction between the classes in the System.IO namespace? In this article I talk about two of the classes available in this namespace, the Directory and DirectoryInfo classes. You will learn how to manipulate directories. You will also learn how to use the properties of those classes to return some useful information.
Contributed by Michael Youssef Rating: / 16 January 29, 2007
Note that we will discuss the classes that manipulate the file system objects, files (discussed in the next article) and directories (folders). The .NET Framework provides us with other classes for reading and writing to files, which will be discussed in a separate article. To get the most out of this article you need to have a good knowledge of C# basics, and of course you need to have VS.NET 2003 installed on your machine.
I will use the F drive on my hard disk for the examples for this article, but you are free to use whatever drive you want. You should use a drive that doesn't contain important files because you may unintentionally delete all the folders and the files on your drive (if you like to play with the code, like me), so be careful. Let's begin our discussion with the Directory and the DirectoryInfo classes.
The Directory and the DirectoryInfo Classes
The Directory and the DirectoryInfo classes are used to represent a folder in the file system. But there are critical differences between the two. The Directory class has only static methods, and it is used when you need to perform just one operation on a folder. Since you don't have to create an object to represent the directory to perform one operation, all of the methods of the Directory class are static, so you perform the operation without creating an instance of that class.
If you need to perform a lot of operations on a folder, it's better to create an object that represents the specific folder. The class DirectoryInfo is used to create an object to represent a folder. It's effective if you are going to perform many operations on the folder because, once the object is created, it has all the necessary information about the folder such as its creation time, last access time and attributes. All the members of the DirectoryInfo class are instance members, unlike the Directory class which contains only static members.
Let's look at an example that uses the DirectoryInfo class. Create a new VS.NET Console Application and name it IOProject, then copy the following code and paste it in the file Class1.cs. Don't forget to replace the F drive with your drive.
using System; using System.IO;
namespace IOProject { class Class1 { static void Main(string[] args) { try { Console.WriteLine("Please enter the name of the folder you want to create or use"); // store the folder name in the dirName variable string dirName = Console.ReadLine(); // create the DirectoryInfo instance DirectoryInfo dInfo = new DirectoryInfo(@"F:" + dirName); // check if the directory doesn't exist, if so then create it if(!dInfo.Exists) { dInfo.Create(); }
Console.WriteLine("How many subfolders you want to create?"); // store the number of subfolders in the variable // subDirs int subDirs = Convert.ToInt32(Console.ReadLine()); // create the subfolders using a for statement for(int i = 1; i <= subDirs; i++) { dInfo.CreateSubdirectory(dirName + i); } Console.WriteLine("The following Subfolders have been" + " created in the folder " + dirName); // get the subfolders using the // DirectoryInfo.GetDirectories() method DirectoryInfo[] dirs = dInfo.GetDirectories(); // printing the subfolders full name foreach(DirectoryInfo subDir in dirs) { Console.WriteLine(subDir.FullName); } } catch(Exception ex) { Console.WriteLine(ex.Message); } finally { Console.ReadLine(); } } } }
Run the application and enter the values that are shown in the next screenshot.
So the folder name is MyFolder and we need to create four subfolders. After you run the application, navigate to MyFolder to take a look at the four new folders.
Let's walk through the code step-by-step. The second statement in the Main method uses the Console.ReadLine() method to get the folder name from the user and stores it in the variable dirName. Next we create a DirectoryInfo object by passing the folder name (stored in the dirName variable) concatenated with the drive letter, so it's much more like "F:MyFolder." Note that instantiating the DirectoryInfo object doesn't create the folder in the File System, so we next use the property DirectoryInfo.Exists to see whether the folder already exists in the File System or not.
If the folder doesn't exist (the property returns false) we create it using the method DirectoryInfo.Create(). If it does exists (the property returns true) we will start manipulating the folder, because we have the folder in the file system and we have created the object that can manipulate it. We have used the operator ! to reverse the Boolean value of the Exists property, so if the directory doesn't exist it returns false and the ! operator reverses the value, causing the if statement to evaluate to true and execute its body.
We use the variable subDirs to store the number of subfolders that will be created in our folder by assigning the return value of the Console.ReadLine() method and converting it to the int data type using the Convert.ToInt32() method. The next for statement creates the subfolders using the CreateSubDirectory() method of the DirectoryInfo instance, which is passed the name of the folder as a string. Note that the method CreateSubDirectory() will do nothing if the subfolder already exists.
So far, so good. We then use the dInfo.GetDirectories() method to return an array of type DirectoryInfo that represents the subfolders of the current folder. Next, we use a foreach statement to iterate through the individual DirectoryInfo objects to write its full name (using the property FullName) to the console using the DirectoryInfo.FullName property. In the next section, we will modify the example a little bit.
Copy the following code and paste it in to replace the previous code example:
using System; using System.IO;
namespace IOProject { class Class1 { static void Main(string[] args) { try { Console.WriteLine("Please enter the name of the folder you want to create or use"); // store the folder name in the dirName variable string dirName = Console.ReadLine(); // create the DirectoryInfo instance DirectoryInfo dInfo = new DirectoryInfo(@"F:" + dirName); // check if the directory doesn't exist, if so then // create it if(!dInfo.Exists) { dInfo.Create(); }
Console.WriteLine("How many subfolders you want to create?"); // store the number of subfolders in the variable // subDirs int subDirs = Convert.ToInt32(Console.ReadLine()); // create the subfolders using a for statement for(int i = 1; i <= subDirs; i++) { dInfo.CreateSubdirectory(dirName + i); } Console.WriteLine("The following Subfolders have been" + " created in the folder " + dirName); // get the subfolders using the // DirectoryInfo.GetDirectories() method DirectoryInfo[] dirs = dInfo.GetDirectories(); // printing the first subfolder information DirectoryInfo firstSDir = dirs[0]; Console.WriteLine(firstSDir.FullName); Console.WriteLine(firstSDir.Name); Console.WriteLine(firstSDir.Root); Console.WriteLine(firstSDir.CreationTime); Console.WriteLine(firstSDir.LastAccessTime); Console.WriteLine(firstSDir.Attributes); firstSDir.Attributes |= FileAttributes.Archive; Console.WriteLine(firstSDir.Attributes); Console.WriteLine("The Folder Extension : " + firstSDir.Extension); } catch(Exception ex) { Console.WriteLine(ex.Message); } finally { Console.ReadLine(); } } } }
Run the code and enter the same values as the previous example.
Because the MyFolder directory already exists, the if statement evaluates to false and the next statement (after the if statement) is executed. We entered the value 4 as before, so the DirectoryInfo.CreateSubDirectories will not create any subfolders (because the subfolders are already there). The difference is that we have replaced the foreach statement with the following code:
The above code prints some useful information about the first subfolder in the MyFolder directory. This information includes the Name property, which returns the name of the folder; the Root property which returns the root; and the CreationTime and lastAccessTime properties are self explanatory.
The Attribute property is used to set or get some useful attributes of the file. Note that you use the | operator to combine those attributes. When we first print the value of the Attributes property we find that there is only one attribute set (Directory). We add another attribute using the FileAttributes Enumeration and print the value of Attributes property again. The Extension property returns an empty string when called on DirectoryInfo instances. The Extension property is inherited, as are much of the methods and properties of this class, from the base class FileSystemInfo. To check that the Extension property returns an empty string you can use the following code:
DirectoryInfo di = new DirectoryInfo(@"F:MyFolder"); if(di.Extension == String.Empty) { Console.WriteLine("Yes Empty String"); }
As we have said, the Directory Class contains only static members and it's best used when you need to perform one or two operations on a specific directory. The idea is that there is no need to instantiate a DirectoryInfo class just to perform one operation on a directory; instead, use the static methods of the Directory Class to perform this operation. The following example uses the Directory Class to list its subdirectories.
Copy and Paste the code in place of the Class1.cs code and press F5 to run the application. You will get the following screenshot:
Because we just need to print out the name of the subdirectories of the directory named MyFolder we have used the Directory.GetDirectories() static method. This method accepts a path to a directory and returns its subdirectories as a string array. Bear in mind that the DirectoryInfo.GetDirectories() method returns an array of DirectoryInfo objects that we can manipulate (as we have done in the previous section). But the Directory.GetDirectories() method returns the subdirectories as an array of strings, and contains only the full name of the subdirectories.
You should also note that the Directory.GetDirectories() accepts the name of the folder that you need to return its subdirectories, whereas the DirectoryInfo.GetDirectories() doesn't accept the folder path because it's working on a specific instance of a directory. Now let's modify the example to return DirectoryInfo objects for the subdirectories of the MyFolder directory.
Passing the Path to Instantiate DirectoryInfo
In the following code we create a DirectoryInfo object by passing the string that returns from the Directory.GetDirectories() method. Let's take a look at the code:
When you run the above code you will get the following screenshot
The only trick in this example is that we have used the string array that returns from calling the Directory.GetDirectories() method to construct DirectoryInfo objects inside the foreach statement. The code simply prints out some of the properties of the DirectoryInfo objects like FullName, CreationTime and Attributes. The Directory Class has methods like GetCreationTime(), GetLastAccessTime(), and GetParent() that correspond to some of the properties of the DirectoryInfo class, but of course there are members that are unique to each class. For example, the Directory.GetCurrentDirectory() returns the directory of the application.
We want to delete some subdirectories in our MyFolder directory. The following code example deletes MyFolder2 and MyFolder4 using the Directory.Delete() method, which accepts a path to the folder that we want it to delete.
There is nothing special about this code except that we have used the String.SubString() method to return the last character in the directory name. That character is a number, so we have converted it from a string data type to an int data type. The if statement evaluates to true if the returned value of the expression dirNum % 2 is 0. So only the folders MyFolder2 and MyFolder4 are deleted because 2 % 2 == 0 and 4 % 2 = 0.