Check for Files and Directories with VB.Net

This is an article on Check for Files and Directories with VB.Net in Visual Basic [VB].

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. Lets see how to perform necessary functions with examples that utilise 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

The following example 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 utilise 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

The next example 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.