An important function of any program is the ability to work
with a file system and manipulate files and directories. In this tip, we
examine how to work with a file system using VB.NET.
We show you a handy way to perform necessary functions with examples that
utilize the existing classes, their methods, and widely used properties.
In order to work with a file system,
we need to use the System.IO
namespace; therefore, we would have a line imports
System.IO at the top of the form or the module.
We’ll focus our attention on the FileInfo
class, which allows you to access and manipulate files on the filesystem. It also lets you determine the files’
properties and DirectoryInfo, a class that
allows you to access and manipulate directories and determine various properties.
Determining if a file exists
Listing A shows how to determine whether a file exists and how
to check one of its properties. In the example, we define the variable sFileName to hold the name and location of the file on the file system. Then
we create an instance of a FileInfo class, which accepts the full file path as a
parameter. Next, we utilize its Exists
property to determine if a file exists. If there is a file, we check and
display the date/time of the file creation; if there is not a file, we display
a message stating that it cannot be located.
Determining if a directory exists
Listing B shows
how to determine whether a directory exists and how to check one of its
properties. We define the variable sDirName to hold the name and location of the Directory on the file system.
Then we create an instance of a DirectoryInfo class,
which accepts the full directory name as a parameter. Next, we utilize its
Exists property to determine if a directory exists. If there is a directory, we
check and display the date/time when it was last accessed; if there is not a
directory, we display a message stating that it cannot be located.
Miss a tip?
Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya’s column.
Advance your scripting skills to the next level with TechRepublic’s free Visual Basic newsletter, delivered each Friday. Automatically sign up today!