File Management in .NET
In two recent articles we looked at file access in the .NET framework—how to write data to and read data from both binary and text files. There’s one more aspect of file programming that a developer needs to know about, and that’s the file management tasks:
- Creating and deleting folders
- Moving, copying, and deleting files
- Getting information about drives, folders, and files
I’m glad to say that the .NET Framework’s approach to file management is well designed and easy to use.
Working with Files
There are two .NET classes that you’ll use for copying, moving, deleting, and getting information about files: the File class and the FileInfo class. Both classes are part of the System.IO namespace. They differ as follows:
- To use the FileInfo class, you must create an instance of the class that’s associated with the file of interest. You then call the appropriate methods to perform operations on that file.
- The File class is an abstract class and cannot be instantiated. You call the File class’s methods and pass as a parameter the name of the file you want to manipulate.
Let’s look at an example of how these two classes differ in usage. Suppose you want to determine the date and time that a file was created. Here’s how you would accomplish this task with FileInfo:
Dim d As DateTime Dim f As New FileInfo("c:\mydatafile.dat") d = f.CreationTime
In contrast, here’s how you would use the File class for the same task:
Dim d As DateTime d = File.GetCreationTime("c:\mydatafile.dat ")
Table 1 describes the members of the File and FileInfo classes that perform frequently needed file-management tasks.
Table 1 Members of the File and FileInfo classes.
File management actions provide many opportunities for exceptions to be thrown. Here are just a few examples:
- Trying to copy a nonexistent file
- Passing a filename/path that’s too long
- Trying to delete a file when you don’t have the required permissions
I advise that you place all file management code in Try..Catch blocks to ensure that unhandled exceptions cannot occur. I won’t go into the details of the possible exceptions here, but you can find the details in the .NET documentation.
Let’s compare some examples of using the File and FileInfo classes. To move the file c:\new_data\report.doc to the folder c:\old_data under the same filename, here’s the code using the FileInfo class:
Dim f As New FileInfo("c:\new_data\report.doc") f.Move("c:\old_data\report.doc")
To perform the same task using the File class, you would write this:
File.Move("c:\new_data\report.doc", " c:\old_data\report.doc")
To delete the file c:\documents\sales.xls, you can use this code:
Or you could use the following code:
Dim f As New FileInfo("c:\documents\sales.xls") f.Delete