CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
// Bind to C:\Windows,
// using a verbatim string.
DirectoryInfo dir2 = new DirectoryInfo(@"C:\Windows");
In the second example, you make the assumption that the path passed into the constructor
(C:\Windows) already exists on the physical machine. However, if you attempt to interact with a
nonexistent directory, a System.IO.DirectoryNotFoundException is thrown. Thus, if you specify a
directory that is not yet created, you need to call the Create() method before proceeding, like so:
// Bind to a nonexistent directory, then create it.
DirectoryInfo dir3 = new DirectoryInfo(@"C:\MyCode\Testing");
dir3.Create();
After you create a DirectoryInfo object, you can investigate the underlying directory contents using
any of the properties inherited from FileSystemInfo. To see this in action, create a new Console
Application named DirectoryApp and update your C# file to import System.IO.
Update your Program class with the following new static method that creates a new DirectoryInfo
object mapped to C:\Windows (adjust your path if need be), which displays a number of interesting
statistics:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Directory(Info) *****\n");
ShowWindowsDirectoryInfo();
Console.ReadLine();
}
static void ShowWindowsDirectoryInfo()
{
// Dump directory information.
DirectoryInfo dir = new DirectoryInfo(@"C:\Windows");
Console.WriteLine("***** Directory Info *****");
Console.WriteLine("FullName: {0}", dir.FullName);
Console.WriteLine("Name: {0}", dir.Name);
Console.WriteLine("Parent: {0}", dir.Parent);
Console.WriteLine("Creation: {0}", dir.CreationTime);
Console.WriteLine("Attributes: {0}", dir.Attributes);
Console.WriteLine("Root: {0}", dir.Root);
Console.WriteLine("**************************\n");
}
}
While your output might differ, you should see something similar to the following:
***** Fun with Directory(Info) *****
***** Directory Info *****
FullName: C:\Windows
Name: Windows
Parent:
Creation: 7/13/2012 10:22:32 PM
757