Using Directory Functions in .NET

Friday Apr 24th 2015 by Peter Shaw

Following what you learned in an earlier column, continue with the I/O theme and take a look at the functionality available in the "Directory" class.

In a previous post, we took a closer look at the static methods available in .NET's file class. In this post, we're going to continue with the I/O theme and take a look at the functionality available in the "Directory" class. Like the file classes, everything in "Directory" is static and contains a large amount of methods for dealing with directories and folders under Windows.

Like the file classes, there also are different areas of operation, four in the case of directory, as follows:

  • Operational
  • Enumeration
  • Attributes
  • Information

The operational functionality deals with creation, copying, deleting, and moving.

Starting with the operational methods, you can create a new directory by using the following code:


which simply creates a single directory called testdir.

Figure 1: The test directory, testdir, has been created

This in itself is not very interesting, however, until we realize that if we provide a whole chain of folders, Windows will actually create the whole chain where folders don't exist; for example:


will do as you expect and create the following tree of subdirectories.

Figure 2: Five subdirectories (subfolders) have been created

The opposite of create is, as expected, "Delete", and, like create, comes in two forms. If you use


It will only delete the folder if the folder is empty. If, however, you pass in the optional boolean flag set to true, it will delete the contents of the folder as well as its subdirectories, but ONLY if those subdirectories themselves are empty. If you try to call the non flag version on a directory that's not empty or the flag version where the subfolders are not empty, an IOException will be thrown.

Directory.Delete(@"d:\testdir", true);

To delete the five folders we created previously, we'd need to make sure '5' was empty, then start at 4 and work backwards to delete the entire tree.

The next method on the list is the same as its counterpart in the File class. "Directory.Exists" will return a boolean flag indicating the existence of a named folder:

   Console.WriteLine("Directory Exists");

The preceding code should, if you've not deleted the folders from the previous example, give you the following output:

Figure 3: The directories exist

"File.Move" is used to move a folder to a new location. If the folder has other folders/files within it, move then will relocate everything from the named directory down over. Like file, it takes two string parameters: a source folder and a destination folder.

Directory.Move(@"d:\testdir", @"d:\testdirtwo");

will move the entire tree to "testdirtwo" at the same location. Word of warning, however; if anything has anything open in the folder to be moved or any of its subfolders, you'll get an IOException that states that it's a security error.

This actually threw me off while I was writing this post, because I misinterpreted the exception as an actual security permissions error. It wasn't until I realised it was simply because Windows Explorer was being nosey and looking to see if there was anything of interest in the folders that I realised it was really a "File/Folder in use by application" exception that I was being given.

One of the major tasks the Directory classes are used for is obtaining lists of files/folders held within them. There are two distinct ways promoted by the libs: the Enumerable way, which, as you might guess, provides an IEnumerable interface allowing you to easily build iterators over your file lists.

The second is the classic "Array" methods; they simply return a list of fixed objects representing the results of the search. Which you decide to use depends exactly on what you hope to achieve.

The enumerable methods all begin with "Enumerate", and there are three versions: one just to enumerate directories, one to just enumerate files, and the third, which enumerates everything.

Each of these has three further variations on the parameters it takes.

IEnumerable Directory.EnumerateDirectories(sourcepath);
IEnumerable Directory.EnumerateDirectories(sourcepath,
IEnumerable Directory.EnumerateDirectories(sourcepath,
   searchPattern, searchOptions);

The others are "EnumerateFiles" and "EnumerateFileSystemEntries".

In this example, we get an enumerable list of strings, containing folder names returned, if we ask just for the sourcepath.

Figure 4: Viewing the sourcepath

The second string parameter is used in a similar method to a traditional wild card; for example, "a*" will return only folders starting with the letter "a". The third version allows you to set things like case sensitivity and ignoring of system/hidden folders. Like many of these optional objects, the full details of all the flags that can be used can be found on the MSDN pages under "".

The non-enumerable entries are the same as the enumerable methods, only prefixed with the word get. For example:


and, like the enumerable methods, have three variations on the parameters they accept. The only difference here is that the "Get" versions return a fixed size array as a result rather than an enumerable list. The operation, otherwise, is completely identical.

The informational group has two methods. "GetLogicalDrives" and "GetParent" get logical drives and return a string list of all the logical drives available in the system the application is being run on.

Figure 5: Result of using the "GetLogicalDrives" method

and get parent, which will return a "System.IO.DirectoryInfo" object containing the parent directory to the directory named in the method's string parameter.

Figure 6: Result of using the "GetParent" method

The remaining methods are the same as those found in the File classes, and are used to get/set attributes from the named directory, and the security info too.

Seen a strange .NET class you want to know more about? What about wanting to know if there's a ".NET Class for that"? Find me on Twitter; just look for a strange I.T. geek that goes by the name of shawty_ds. Let him know and it might get featured in a future edition of this column.

Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved