Directory vs DirectoryInfo

Afshar Mohebi picture Afshar Mohebi · Jun 30, 2010 · Viewed 51.7k times · Source

Are they equivalent or alternatives to each other? Is any of them deprecated and if so, which one? Which one is recommended for use in an ASP.NET web application? My aim is to extract all files from a specific directory recursively.

Answer

Josh picture Josh · Jun 30, 2010

Directory is a static class that provides static methods for working with directories. DirectoryInfo is an instance of a class that provides information about a specific directory. So for example, if you wanted the information about C:\Temp:

var dirInfo = new DirectoryInfo("C:\\Temp");
if (dirInfo.Exists) {
    FileInfo[] files = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);
    ...
}

If you just wanted the names as strings, it might be quicker and easier to avoid creating an instance of DirectoryInfo by using the static methods of Directory.

if (Directory.Exists("C:\\Temp")) {
    string[] files = Directory.GetFiles("C:\\Temp", "*.*", SearchOption.AllDirectories);
    ...
}

In short, it really doesn't matter which you use as long as it does what you want. Neither is recommended over the other.