Access the File System with .NET Framework Classes from Visual Basic 6
Scott Swigart
Swigart Consulting LLC.
Applies to:
Microsoft Visual Basic 6
Microsoft Visual Basic 2005
Microsoft Visual Basic .NET 2003
Summary: Accessing the file system is a common application requirement, and in the spirit of Microsoft Visual Basic Fusion, this article shows how to access some of the best Microsoft .NET Framework file system functionality from existing Visual Basic 6 applications. Learn how to get the extension for a file, the directory portion or a path, or the file name portion of a path. Learn how to fire events every time the contents of a directory change. (16 printed pages)
Download the Visual Basic Fusion—IO_IO.msi code sample for this article.
Introduction
Primer: Calling .NET from Visual Basic 6
Using the Path Class from Visual Basic 6
Using the FolderBrowserDialog from Visual Basic 6
Using the FileSystemWatcher from Visual Basic 6
Examining the Construction of IOLib
Conclusion
Additional Resources
Accessing the file system is a common application requirement, and in the sprit of Visual Basic Fusion, this article will show you how you can access some of the best .NET Framework file system functionality from existing Visual Basic 6 applications.
First, there's the Path class. This class makes it a snap to work with, and extract pieces of file system path strings. With one line of code, you can get the extension for a file, or get the directory portion of a path, or get the file name portion of a path. You can even switch a file extension, or determine if a path is relative or absolute.
Next, there's the FolderBrowserDialog class, which makes it easy to display a dialog box that lets the user pick a folder path.
Figure 1. Folder Browser dialog box
Displaying this system dialog box from Visual Basic 6 requires a good amount of Win32 API calls. However, by using the IOLib included with this article (written in Visual Basic 2005), you can easily display this dialog box from a Visual Basic 6 application.
Finally, this article will examine the FileSystemWatcher class. This class can fire events every time the contents of a directory change. So if you have an application that needs to process new files as they appear or change, this is a great class to use. And again, it can be used easily from Visual Basic 6.
In general, you cannot call classes from Visual Basic 6 directly into the .NET Framework because the .NET Framework classes do not expose themselves as COM objects. However, you can use Visual Basic 2005 to create COM wrappers for the portions of the .NET Framework that you want to use. Your Visual Basic 6 code calls into your COM wrapper, and the COM wrapper calls into the .NET framework.
Figure 2. Calling into the .NET Framework with wrapper classes
This is the approach used in this article. The sample code for this article includes a Visual Basic 2005 project called IOLib that is a wrapper for the .NET Framework Path class, FolderBrowserDialog class, and FileSystemWatcher class. This article will initially show how you can use IOLib from your Visual Basic 6 applications. If you're interested in how IOLib was constructed, the article will finish off with a walkthrough on building your own wrapper classes.
Sometimes, an application needs to manipulate a file path string. For example, you might have a full path to a file, but you want to just get the directory portion of the path. Other times, you may want just the file name, without the directory information. Other times, you may want to examine the file extension so that you can take different action for different file types. You may even want to change the extension for a file if you are loading it from one format and saving it with a different one.
The Path class exists to make these kinds of operations very simple. The IOLib included with this article wraps the .NET Path class so that you can call it from Visual Basic 6 or other COM based environments. Through this COM wrapper, you can access the following functionality:
Table 1. COM wrapper functionality
Property or Method | Description |
---|---|
ChangeExtension | Changes the extension of a path string. |
Combine | Combines two path strings. |
GetDirectoryName | Returns the directory information for the specified path string. |
GetExtension | Returns the extension of the specified path string. |
GetFileName | Returns the file name and extension of the specified path string. |
GetFullPath | Returns the absolute path for the specified path string. |
GetPathRoot | Gets the root directory information of the specified path. |
GetTempFileName | Returns a uniquely named zero-byte temporary file on disk and returns the full path to that file. |
GetTempPath | Returns the path of the current system's temporary folder. |
HasExtension | Determines whether a path includes a file name extension. |
IsPathRooted | Gets a value indicating whether the specified path string contains absolute or relative path information. |
InvalidPathChars | Provides a platform-specific array of characters that cannot be specified in path string arguments passed to members of the Path class. |
The following walkthrough will illustrate using Path class from Visual Basic 6.
Prior to completing this walkthrough, you must install Visual Studio 2005, Visual Basic Express. Visual Basic Express is a free and relatively small download, and can install along side of Visual Studio 6.0, Visual Studio .NET, Visual Studio 2003, or Visual Studio 2005, without any problems.
Walkthrough: Using the Path class from Visual Basic 6
If you have not already run the install for the sample code, in the sample code folder for this article, navigate into the Code sub-folder, and double-click install.bat.
This registers the .NET framework DLLs, and the IOLib wrapper so that it can be used from Visual Basic 6.0
Start Visual Basic 6.0.
In the New Project dialog box, select Standard EXE, and click Open.
Right-click on the Toolbox, and select Components...
In the Components dialog box, check Microsoft Common Dialog Control 6.0.
Click OK.
Select the Project | References menu command.
Check IOLib.
Click OK.
You have now referenced the .NET DLLs needed to display the folder browser dialog box from Visual Basic 6. It's now time to build the user interface.
In the Toolbox, double-click the CommonDialog control to add it to the form.
Add a TextBox to the form, and resize it so that it fills most of the form.
In the Properties window, for the Text1 control, set the following properties:
Multiline = True
Text = (an empty string)
This text box will display information about a selected file using the Path class.
Right-click on the Form, and select View Code.
Enter the following code:
Private Sub Form_Load() Dim path As New IOLib.PathWrapper With CommonDialog1 .ShowOpen If .FileName <> "" Then Text1 = "Directory: " & path.GetDirectoryName(.FileName) & _ vbCrLf Text1 = Text1 & "Has extension: " & _ path.HasExtension(.FileName) & vbCrLf Text1 = Text1 & "Extension: " & _ path.GetExtension(.FileName) & vbCrLf Text1 = Text1 & "FileName: " & _ path.GetFileName(.FileName) & vbCrLf Text1 = Text1 & "Root: " & _ path.GetPathRoot(.FileName) & vbCrLf Text1 = Text1 & "Absolute or Relative: " & _ IIf(path.IsPathRooted(.FileName), "Absolute", "Relative") End If End With End Sub
Press F5 to run the application
As you can see, when you select a file, this application shows you a number of things about that file path.
Figure 3. Using the Path class from Visual Basic 6
With just a line of code, the application can separate the file name from the directory path. The application can also determine if the file has an extension, and what the extension is. Finally, the application can tell you the root folder for the path, and whether the path is relative or absolute. With Visual Basic 6, you are often required to do your own string splitting logic to get these pieces of information, and it's easy to introduce bugs if the user provides UNC paths, or other path formats that your application may not expect. Not only is the Path class easier than writing your own logic, but it's also been tested against a wide range of paths.
The folder browser dialog box is very useful when you need the user to select a folder (rather than a specific file). The operating system includes a built-in folder browser dialog box, but Visual Basic 6 does not provide access to this dialog box. If you want to display the folder browser with Visual Basic 6, you need to call the SHBrowseForFolder and other Win32 API functions.
However, the .NET Framework does contain a FolderBrowserDialog class, and the IOLib code included with this article wraps the FolderBrowserDialog class so that it can easily be used from Visual Basic 6. The IOLib FolderBrowserDialogWrapper exposes the following functionality:
Table 2. FolderBrowserDialogWrapper functionality
Property or Method | Description |
---|---|
Description | Gets or sets the descriptive text displayed above the tree view control in the dialog box. |
Reset | Resets properties to their default values. |
RootFolder | Gets or sets the root folder where the browsing starts from. |
SelectedPath | Gets or sets the path selected by the user. |
ShowDialog | Displays the folder browser dialog box. |
ShowNewFolderButton | Gets or sets a value indicating whether the New Folder button appears in the folder browser dialog box. |
The following steps illustrate using the FolderBrowserDialog class from Visual Basic 6:
Walkthrough: Using the .NET FolderBrowserDialog from Visual Basic 6
If you have not already run the install for the sample code, in the sample code folder for this article, navigate into the Code sub-folder, and double-click install.bat.
This registers the .NET framework DLLs, and the IOLib wrapper class so that it can be used from Visual Basic 6.0.
Start Visual Basic 6.0.
In the New Project dialog, select Standard EXE, and click Open.
Select the Project | References menu command.
Check IOLib, and System.Windows.Forms.DLL.
Click OK.
You have now referenced the .NET DLLs needed to display the folder browser dialog box from Visual Basic 6. It's time to write some code.
Double-click Form1 in the designer to cause Visual Basic to generate the Form_Load subroutine and switch you to the code editor.
Inside of Form_Load, enter the following code:
Dim fb As New IOLib.FolderBrowserDialogWrapper fb.Description = "Select a folder" fb.ShowNewFolderButton = True fb.RootFolder = SpecialFolderWrapper_ProgramFiles If fb.ShowDialog = DialogResult_OK Then MsgBox fb.SelectedPath End If
This creates an instance of the box class. This wrapper is then used to configure properties such as the description text and starting folder. The folder browser is also configured to allow the user to create a new folder through the dialog box. Finally, the dialog box is shown, and if the user clicks the OK button, the path selected in the dialog box is processed.
Press F5 to run the application. The following dialog box should appear:
Figure 4. Displaying the folder browser dialog box from Visual Basic 6
When a folder is selected, you should see the path to the folder appear in the message box.
Figure 5. Displaying the folder selected by the user
You can see that displaying the folder browser dialog box from Visual Basic 6 using the .NET Framework is much easier than displaying it using Win32 API calls.
I've probably saved the best for last. The Microsoft .NET Framework includes a class called the FileSystemWatcher, which will raise an event any time files in a folder are created, deleted, changed, or renamed. Normally, you can't use the FileSystemWatcher directly from Visual Basic 6, but IOLib (supplied with this article) wraps the FileSystemWatcher, making it simple to use from COM environments.
The following walkthrough will show you how to use the FileSystemWatcher to detect changes under a directory.
Walkthrough: Using the FileSystemWatcher from Visual Basic 6
If you have not already run the install for the sample code, in the sample code folder for this article, navigate into the Code sub-folder, and double-click install.bat.
This registers the .NET framework DLLs, and the IOLib wrapper class so that it can be used from Visual Basic 6.0
Create a new folder on your hard disk called C:\WatchedFolder. This folder will be monitored by the FileSystemWatcher for changes.
Start Visual Basic 6.0.
In the New Project dialog box, select Standard EXE, and click Open.
Select the Project | References menu command.
Check IOLib.
Click OK.
You have now referenced the .NET DLLs needed to use the FileSystemWatcher class from Visual Basic 6.
Add a CommandButton and TextBox to the form.
For the CommandButton, set the text property to Start Watching.
For the TextBox:
- Set the Text property to blank.
- Set the MultiLine property to True.
Double-click the Form to have Visual Basic generate the Form_Load event handler, and switch you into Code view.
In the General Declarations section (above Form_Load), enter the following:
Private WithEvents fsw As IOLib.FileSystemWatcherWrapper
In the Form_Load event, enter the following:
Set fsw = New IOLib.FileSystemWatcherWrapper
At this point, you have created an instance of the class that will be used to monitor the C:\WatchedFolder for any changes.
From the Object drop-down, select Command1.
Figure 6. Selecting the command button with the Object drop-down
This will generate the click event for the CommandButton control.
In the Command1_Click event, enter the following code:
fsw.InitWatcher ("C:\WatchedFolder") fsw.IncludeSubDirectories = True fsw.EnableRaisingEvents = True
This tells the FileSystemWatcher which folder it should monitor. It also indicates that any sub-directories of that folder should also be watched. Finally, it tells the FileSystemWatcher to begin raising events as soon as anything changes.
The only remaining task is wiring up event handlers to process any changes.
From the Object drop-down, select fsw.
This generates the fsw_Changed event handler, which will fire any time a file under the C:\WatchedFolder directory changes.
In the fsw_Changed event handler, enter the following code:
Text1 = Text1 & "Changed: " & e.FullPath & vbCrLf
In the Procedure drop-down, select Created.
Figure 7. Selecting the Created event with the procedure drop down
This will generate the fsw_Created event handler. This event fires whenever a new file appears under the C:\WatchedFolder directory.
In the fsw_Created event handler, enter the following code:
Text1 = Text1 & "Created: " & e.FullPath & vbCrLf
Repeat steps 18 and 19 to create event handlers for the Deleted and Renamed events. Your final code should appear as:
Private WithEvents fsw As IOLib.FileSystemWatcherWrapper Private Sub Command1_Click() fsw.InitWatcher ("C:\WatchedFolder") fsw.IncludeSubDirectories = True fsw.EnableRaisingEvents = True End Sub Private Sub Form_Load() Set fsw = New IOLib.FileSystemWatcherWrapper End Sub Private Sub fsw_Changed(ByVal e As IOLib.FileSystemEventArgsWrapper) Text1 = Text1 & "Changed: " & e.FullPath & vbCrLf End Sub Private Sub fsw_Created(ByVal e As IOLib.FileSystemEventArgsWrapper) Text1 = Text1 & "Created: " & e.FullPath & vbCrLf End Sub Private Sub fsw_Deleted(ByVal e As IOLib.FileSystemEventArgsWrapper) Text1 = Text1 & "Deleted: " & e.FullPath & vbCrLf End Sub Private Sub fsw_Renamed(ByVal e As IOLib.FileSystemEventArgsWrapper) Text1 = Text1 & "Renamed: " & e.FullPath & vbCrLf End Sub
Press F5 to run the application.
Click Start Watching.
Open Windows Explorer and navigate to the C:\WatchedFolder directory.
Select the File | New | Text document menu command.
This creates a new file in the folder, and should trigger an event in your application.
Rename the new file to test.txt.
Delete test.txt.
Switch to your application. It should appear as follows:
Figure 8. Output from the Visual Basic 6 application using the FileSystemWatcher
You can see that the application was able to monitor the directory for any changes, and the changes are displayed in the text box. Often this is used for batch processing of files as they are uploaded, exported from a mainframe, or are otherwise placed into a "drop" folder.
In the code download provided with this article you will find a folder called IOLib. Double-clicking the IOLib.sln file in that folder will open the solution in Visual Studio 2005 or Visual Basic Express.
When the solution opens, you will be able to see the various wrapper classes listed in the Solution Explorer.
Figure 9. Wrapper classes listed in the Solution Explorer
Double-clicking on any of these wrapper classes will open the file in the code editor. If, for example, you double-click the FolderBrowserDialogWrapper.vb file, you will see the following code:
Imports System.Windows.Forms <ComClass(FolderBrowserDialogWrapper.ClassId, FolderBrowserDialogWrapper.InterfaceId, FolderBrowserDialogWrapper.EventsId)> _ Public Class FolderBrowserDialogWrapper #Region "COM GUIDs" Public Const ClassId As String = "705DDB3F-3A03-4C97-ACE4-9D6F4A50F0AC" Public Const InterfaceId As String = "CB311CDB-B62A-444E-B415-A253EB579541" Public Const EventsId As String = "E6B1B7BF-F65B-4A56-9534-5C39332332FB" #End Region Private _folderBrowser As FolderBrowserDialog Public Sub New() MyBase.New() _folderBrowser = New FolderBrowserDialog End Sub Public Property Description() As String Get Return _folderBrowser.Description End Get Set(ByVal Value As String) _folderBrowser.Description = Value End Set End Property Public Sub Reset() _folderBrowser.Reset() End Sub Public Property RootFolder() As SpecialFolderWrapper Get Return _folderBrowser.RootFolder End Get Set(ByVal Value As SpecialFolderWrapper) _folderBrowser.RootFolder = Value End Set End Property Public Property SelectedPath() As String Get Return _folderBrowser.SelectedPath End Get Set(ByVal Value As String) _folderBrowser.SelectedPath = Value End Set End Property Public Function ShowDialog() As DialogResult Return _folderBrowser.ShowDialog End Function Public Property ShowNewFolderButton() As Boolean Get Return _folderBrowser.ShowNewFolderButton End Get Set(ByVal Value As Boolean) _folderBrowser.ShowNewFolderButton = Value End Set End Property End Class
There are a couple of important things to note in this class. First, you can see that the class uses the ComClass attribute, and contains a number of GUIDs. These insure that this class can be properly registered as a COM object, and be usable from Visual Basic 6. Next, the class just provides simple wrappers that pass through to the underlying .NET Framework FolderBrowserDialog class. When the user calls ShowDialog of the wrapper, ShowDialog of the FolderBrowserDialog class is called. When the user sets the Description property of the wrapper, the Description property of the FolderBrowserDialog is set. In most cases, there's nothing overly complicated about the wrapper classes. Their main purpose is to expose a COM interface, and pass-through to the desired .NET framework class.
The following walkthough will take you, step-by-step, through the creation of a minimal wrapper around the FolderBrowserDialog, to further your understanding of wrapper construction.
Walkthrough 4: Constructing a wrapper for the FolderBrowserDialog.
The first task will be to create the wrapper class. Once it is created, you will use it from Visual Basic 6.
(Visual Basic Express Only) Copy the ComClass.zip file from the code download for this article to C:\Documents and Settings\[User Name]\My Documents\Visual Studio 2005\Templates\ItemTemplates\Visual Basic
Start Microsoft Visual Basic 2005 Express Edition, or Microsoft Visual Studio 2005.
Select the File | New Project menu command.
The wrapper class will be a class library project. This will compile to a DLL, much like a COM component would.
In the New Project dialog box:
- (VS 2005 Only) For Project Types, select Visual Basic Projects.
- For Templates, select Class Library.
- For Name, enter FBWrapper.
- Click OK.
In the Solution Explorer, right-click Class1.vb and select Delete.
Click OK.
Class1 is not needed because it is a simple .NET class, but not a COM class. For the wrapper, we need to create a COM class so that it can be used as a COM object from Visual Basic 6.
Select the Project | Add New Item menu command.
In the Add New Item dialog box:
- For Templates, select COM Class.
- For Name enter FolderBrowserDialogWrapper.
- Click OK.
This has created the beginning of the wrapper class. Now you need to write the code that will wrap the FolderBrowserDialog class.
Select the Project | Add Reference menu command.
In the Add Reference dialog box:
- Click System.Windows.Forms.dll.
- Click Select.
- Click OK.
Above the Public Sub New constructor, enter the following line of code:
Private fb As New System.Windows.Forms.FolderBrowserDialog This creates an instance of the FolderBrowserDialog which you are wrapping.
After Public Sub New, but before End Class, enter the following:
Public Function ShowDialog() As System.Windows.Forms.DialogResult Return fb.ShowDialog() End Function
When the ShowDialog function in your wrapper is called, it will pass the call through to the underlying FolderBrowserDialog class.
Enter the following code to create a property that will allow your Visual Basic 6 application to determine which folder was selected.
Public Property SelectedPath() As String Get Return fb.SelectedPath End Get Set(ByVal Value As String) fb.SelectedPath = Value End Set End Property
Select the Build | Build FBWrapper menu command.
At this point, your wrapper is complete and can be used from Visual Basic 6.
Start Visual Basic 6.
In the New Project dialog box, select Standard Exe, and click Open.
Select the Project | References menu command.
In the References dialog box, check FBWrapper, and click OK.
You can see that your wrapper class appears in Visual Basic 6 just like any other COM object. You can just reference and use it.
Double-click the form to have the development environment generate the Form_Load event handler, and switch you to the code editor.
In the Form_Load event, enter the following code:
Dim fb As New FBWrapper.FolderBrowserDialogWrapper fb.ShowDialog MsgBox fb.SelectedPath
This creates an instance of the wrapper class, and displays the folder browser dialog box. When the user selects a folder, the selected folder is displayed in a message box.
Press F5 to run the application and display the folder browser.
Feel free to examine the other wrapper classes in IOLib, and you will see that they are built exactly this way. They simply provide a COM interface, and pass calls through to the underlying .NET framework classes.
In this article, you have seen that the .NET Framework exposes a number of classes that are very useful when working with the file system. The Path class makes it easy to work with file path strings and extract specific pieces of information, such as the directory name, file name, and file extension. The FolderBrowserDialog provides easy access to the system dialog box that allows the user to select a folder. Finally, the file system watcher class makes it easy to monitor folders for new files or changes. This article also includes a component called IOLib that wraps these .NET classes, making them usable from Visual Basic 6 or other COM environments, like Visual Basic for Applications (VBA), ASP, or Visual Basic Scripting Edition (VBScript).
Scott Swigart (www.swigartconsulting.com) spends his time consulting with companies on how to best use today's technology and prepare for tomorrows. Along this theme, Scott is a proud contributor to the Visual Basic Fusion site, as it offers information and tactics of real use for Visual Basic developers who want to build the most functionality with the least effort. Scott is also a Microsoft MVP, and co-author of numerous books and articles. If you have any question or comments about this article, feel free to send e-mail to scott@swigartconsulting.com.