There's a parallel set of classes to Directory and DirectoryInfo that enables you to work with files File and FileInfo . The File class works with files in general, and the FileInfo class works with a specific file. Like Directory , File is a static class, and you can see the significant public methods of this class in Table 5.4, which let you create files, delete them, move them, and more. Table 5.4. Significant Static Public File Methods
You can see the significant public properties of the FileInfo class in Table 5.5 and its significant public methods in Table 5.6. Table 5.5. Significant Public FileInfo Properties
Table 5.6. Significant Public FileInfo Methods
Here's an example using the FileInfo class to determine the name, length, and last modified date of all the files in the current directory. You can use the GetFiles method of a DirectoryInfo object to get an array of FileInfo objects. We loop over that array in ch05_02.cs, Listing 5.2, displaying the filenames and last-modified times. Listing 5.2 Getting File Information (ch05_02.cs)using System.IO; class ch05_02 { public static void Main() { string currentDirectory = System.Environment.CurrentDirectory; DirectoryInfo dir = new DirectoryInfo(currentDirectory); FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { System.Console.WriteLine( "{0} is {1} bytes long, last modified {2}.", file.Name, file.Length, file.LastWriteTime); } } } Here's the kind of display you see when you run ch05_02.cs: C:\>ch05_02 ch05_02.cs is 518 bytes long, last modified 2/17 2:00:04 PM. ch05_02.exe is 3584 bytes long, last modified 2/17 2:00:06 PM. Here's another example, using the DirectoryInfo method CreateSubdirectory to create a new subdirectory named backup , and the FileInfo CopyTo method to copy all files in the current directory to the backup directory. You can see how this code works in ch05_03.cs, Listing 5.3. Listing 5.3 Copying Files (ch05_03.cs)using System.IO; class ch05_03 { public static void Main() { string currentDirectory = System.Environment.CurrentDirectory; DirectoryInfo dir = new DirectoryInfo(currentDirectory); DirectoryInfo backupDirectory = dir.CreateSubdirectory("backup"); FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { string newName = backupDirectory.FullName + @"\" + file.Name; file.CopyTo(newName); } } } As you can see, the Directory , DirectoryInfo , File , and FileInfo classes enable you to work with directories and files without actually handing the data inside a file. As such, they provide only external services when handling your data; to open files and access their contents directly, you use streams. |