CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
// Prints path to ..\MyFolder2\Data.
Console.WriteLine("New Folder is: {0}", myDataFolder);
}
Working with the Directory Type
You have seen the DirectoryInfo type in action; now you’re ready to learn about the Directory type. For
the most part, the static members of Directory mimic the functionality provided by the instance-level
members defined by DirectoryInfo. Recall, however, that the members of Directory typically return
string data rather than strongly typed FileInfo/DirectoryInfo objects.
Now let’s look at some functionality of the Directory type; this final helper function displays the
names of all drives mapped to the current computer (using the Directory.GetLogicalDrives() method)
and uses the static Directory.Delete() method to remove the \MyFolder and \MyFolder2\Data
subdirectories created previously.
static void FunWithDirectoryType()
{
// List all drives on current computer.
string[] drives = Directory.GetLogicalDrives();
Console.WriteLine("Here are your drives:");
foreach (string s in drives)
Console.WriteLine("--> {0} ", s);
// Delete what was created.
Console.WriteLine("Press Enter to delete directories");
Console.ReadLine();
try
{
Directory.Delete(@"C:\MyFolder");
// The second parameter specifies whether you
// wish to destroy any subdirectories.
Directory.Delete(@"C:\MyFolder2", true);
}
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
Source Code You can find the DirectoryApp project under the Chapter 20 subdirectory.
Working with the DriveInfo Class Type
The System.IO namespace provides a class named DriveInfo. Like Directory.GetLogicalDrives(), the
static DriveInfo.GetDrives() method allows you to discover the names of a machine’s drives. Unlike
Directory.GetLogicalDrives(), however, DriveInfo provides numerous other details (e.g., the drive
760