BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET 3.5+
.NET 3.5+

Retrieve Drive, File and Folder Names

Many software projects involve interaction with the file system. When this requires that a list of drive letters is generated, or that a drive or folder's files and subfolders are retrieved, the Directory class can be used to obtain the list.

Obtaining the Folders Within a Folder

If you want to retrieve a list of subfolders within a folder you can use the GetFolders method. This has the same three overloads as GetFiles, each returning a string array. For example, the following obtains a list of all subfolders of c:\test, including all subdirectories.

var folders = Directory.GetDirectories(@"c:\test", "*.*", SearchOption.AllDirectories);

/* RESULTS

c:\test\d1
c:\test\d2
c:\test\d2\d3

*/

Obtaining all File Entries in a Folder

The final "Get" method combines the results of GetFiles and GetFolders in a single call. GetFileSystemEntries has the same three overloaded versions and, as with the previous methods, can be used in the .NET framework version 1.1.

var files = Directory.GetFileSystemEntries(@"c:\test", "*.*", SearchOption.AllDirectories);

/* RESULTS

c:\test\d1
c:\test\d2
c:\test\f1.txt
c:\test\f2.txt
c:\test\d1\f3.txt
c:\test\d1\f4.txt
c:\test\d2\d3
c:\test\d2\f5.txt
c:\test\d2\f6.txt
c:\test\d2\d3\f7.txt
c:\test\d2\d3\f8.txt

*/

Enumerate Methods

In .NET 3.5, three new methods were added to the Directory class. Each has the same overloaded versions as the GetFiles, GetFolders and GetFileSystemEntries methods and each returns the same results. The methods are named EnumerateFiles, EnumerateFolders and EnumerateFileSystemEntries. The key difference is that the results are returned as IEnumerable<string> objects, rather than arrays. The methods provide greater performance and efficiency than the "Get" equivalents, as the results can be enumerated before the entire list is generated.

var files = Directory.EnumerateFileSystemEntries(
    @"c:\test", "*.*", SearchOption.AllDirectories);

/* RESULTS

c:\test\d1
c:\test\d2
c:\test\f1.txt
c:\test\f2.txt
c:\test\d1\f3.txt
c:\test\d1\f4.txt
c:\test\d2\d3
c:\test\d2\f5.txt
c:\test\d2\f6.txt
c:\test\d2\d3\f7.txt
c:\test\d2\d3\f8.txt

*/
25 June 2011