You have now seen reading and writing with files, but Visual Basic .NET (through the .NET Framework classes) provides a large set of useful file operations outside of the stream classes. This section looks at how to find, create, and delete directories and files.
As I briefly discussed in Chapter 2, “Visual Basic .NET Language Changes,” the .NET Framework is divided into a series of namespaces and each of the namespaces contains a number of related classes. The file and directory (and stream) classes are bundled into the System.IO namespace. The System.IO namespace is, as you might gather from the name, all about input and output. The System.IO namespace is one of the most heavily used namespaces in the .NET Framework for this reason. Anytime you want to open, read from, write to, or otherwise deal with a file or stream, you need this namespace. Fortunately, the System.IO namespace is included inside System.DLL and Visual Basic .NET includes a reference to System.DLL by default in any new project, so you should always have the IO classes available.
If you look in the online help at the System.IO namespace, you will see two classes named File and Directory. These two classes map to files and directories, as you probably gathered from the name, and using their methods, you can work with the file system. For example, the Directory class has methods for retrieving subdirectories, getting the list of files in the directory, and so on, whereas the File class has methods for copying a file, deleting a file, and for retrieving file information. Table 4.5 lists the important methods of the Directory object and Table 4.6 shows the important methods of the File class.
The methods of the File and Directory classes are Shared, which means that you don't have to create an object to use them. To work with a Shared class member, you simply use the class name to access them. For example, because the Exists method of the File class is Shared, you do not need to declare an instance of the File class to access it; you just use the File class itself. So, rather than writing this:
Dim isMyFileThere As Boolean Dim oFile As New File() isMyFileThere = oFile.Exists("somefile.txt")
You determine whether a file exists with the following code:
Dim isMyFileThere As Boolean isMyFileThere = File.Exists("somefile.txt")
Another key class used for working with the file system is also located in the System.IO namespace, Path. As the name implies, Path provides a set of useful functions (all shared like the File and Directory classes) used for working with file paths. Table 4.7 lists the various methods of the Path class, along with brief explanations.
I will not go into any more detail on the File, Directory, or Path classes, but a demo application that shows some of the functionality of these classes is included on this book's Web site.
18.188.83.242