Browse, Open, and Save Dialogs

Level:
Level1

Often when writing a VB.NET application we need to either open a file from the system or save a file to the system somewhere (many times both). Other times we need to browse for a folder instead of a file. Each one of these can be accomplished with a different Common Dialog that ships with VB.NET. To open a file we use the OpenFileDialog control. To save a file we use the SaveFileDialog control. Lastly, to browse for a folder we can use the FolderBrowserDialog. This tutorial and source sample demonstrates how to make use of each of this VB.NET common dialogs.


Source Sample

This tutorial walks through a portion of a Visual Basic .NET source code sample. It is suggested that you download the file and look at the code as it is explained in this tutorial. Note we will be focusing on the code in the following buttons: Open a file, Save a file, Browse Folders, and Retrieve Multiple Files (on the second tab).

image    image

As we go through each one of these snippets of the source code will be listed in line with the tutorial. However, by looking at the code yourself you will see detailed comments that help explain each area.


Opening a file with the OpenFileDialog

As the name suggests we can use the OpenFileDialog control to show a built in Windows common dialog in which the user can select the file they want to have opened. To do this we simply drag the OpenFileDialog control from the toolbox onto our form.

image

Once this control is on our form we can give it a name and begin to use it. On our sample we named it: odlgTextFile. The Open File Dialog has many properties to help us customize how it behaves. We are going to set a few of these to give you an idea of some of the things we can customize when opening a file (MainForm.vb – Line 12):

With odlgTextFile
	.CheckFileExists = True
	.CheckPathExists = True
	.DefaultExt = "txt"
	.DereferenceLinks = True
	.Filter = _
		"Text files (*.txt)|*.txt|All files|*.*"
	.Multiselect = False
	.RestoreDirectory = True
	.ShowHelp = True
	.ShowReadOnly = False
	.ReadOnlyChecked = False
	.Title = "Select a file to open"
	.ValidateNames = True
End With

Here is a description of what each of these properties does:

  • CheckFileExists – Tells windows to make sure that the file that’s selected does in fact exist
  • CheckPathExists – Again tells windows to verify the path exists
  • DefaultExt – This is the extension type you want selected by default (notice leave the . off)
  • DerefrenceLinks – This makes it so that if the user selects a link to a file the actual file is returned
  • Filter – This is what shows up in the filter drop down list. Notice its description, file type, separated by |’s
  • Multiselect – This makes it so they can only select one file
  • RestoreDirectory – If you set this to false (the default) then whatever directory they are on when they open the file will be saved off and used for future file opens.
  • ShowHelp – Makes the help button appear in the dialog
  • ShowReadOnly – Makes the checkbox appear that lets the user say to open the file in ReadOnly mode
  • ReadOnlyChecked – Sets if this checkbox is checked or not by default
  • Title – Is the title that appears in the dialogs header
  • ValidateNames – Makes it so that we only accept valid Win32 file names.
  • So now we have our dialog all set up and ready to go the next thing we need to do is show the dialog and read the file that is selected:

    If .ShowDialog = Windows.Forms.DialogResult.OK Then
    	Try
    		txtFileContents.Text = My.Computer.FileSystem.ReadAllText(.FileName)
    	Catch fileException As Exception
    		Throw fileException
    	End Try
    End If

    Notice that the ShowDialog method takes no parameters and returns if the user clicked the Ok button or not. If the user did select a file and clicked ok then we try to open the file and set our TextBox to its contents. If for some reason there is an error doing this then we throw an exception. That’s all there is too it we can easily allow our users to open files from our VB.NET program.


    Saving a file with the SaveFileDialog

    The user of your program has spent hours creating the perfect thing. Now they don’t want to lose it when they restart the computer. They are looking for the all important search feature. They need to be able to select a folder and type in a filename to save what they are working on to the hard drive. How do you as a VB.NET developer give them this. Simple – use the SaveFileDialog control.

    To begin using this control all we need to do is select it from the control toolbox and drag it onto our form. In our sample we named ours sdlgTextFile.

    image

    Next we need to hook up our Save button to make use of this control. To see this in action check out the click event handler for the Save File button in our sample (around line 77).

    With sdlgTextFile
    	.AddExtension = True
    	.CheckPathExists = True
    	.CreatePrompt = False
    	.OverwritePrompt = True
    	.ValidateNames = True
    	.ShowHelp = True
    	.DefaultExt = "txt"
    	.FileName = filename
    	.Filter = _
    		"Text files (*.txt)|*.txt|" & _
    		"All files|*.*"
     
    	If .ShowDialog() = Windows.Forms.DialogResult.OK Then
    		My.Computer.FileSystem.WriteAllText(.FileName, _
    			txtFileContents.Text, False)
    	End If
    End With

    Some of the properties we are setting are the same as the OpenFileDialog above. However, some of them are specific to this dialog:

    • AddExtension – If the user just types a filename the DefaultExt will be appended
    • CreatePrompt – Prompts the user if they want to create the file
    • OverwritePrompt – If the file already exists Windows will ask the user if they want to overwrite it

    Notice once again we call the ShowDialag method and check the return value to see if the user clicked the Ok button. If they did then we write our textBox contents to the file they specified.


    Browsing Folders with the FolderBrowserDialog

    Sometimes we want to allow our users to select a folder (either for us to read from or to write to). This is different from the File Dialogs as we don’t want to force the user to select a file within a folder but rather just the folder. Microsoft Windows has a common dialog for this and we can make use of it in VB.NET with the FolderBrowserDialog. To use this we once again drag the control from the toolbox onto our form.

    image

    Once the FolderBrowserDialog is on your form give it a name (ours is fldlgList) and once again we will hook up our Browse Folders button to interact with it (See line 264).

    With fldlgList
    	.RootFolder = Environment.SpecialFolder.Personal
    	.Description = "Select the directory you want to use as the default."
    	.ShowNewFolderButton = True
     
    	If .ShowDialog = Windows.Forms.DialogResult.OK Then
    		txtDirectory.Text = .SelectedPath
    	End If
    End With

    By now you should be getting pretty used to this code. We take our FolderBrowserDialog and set its RootFolder to where we want to the path we want the dialog to show when it starts up. We also give it a description and we tell it to allow the user to add a new folder with the built in NewFolder button.

    Our final code is like the other dialogs. We verify that the user clicked the ok button and then we store away the SelectedPath that the user chose. Obviously in a real application we would do something with this path.


    Select Multiple Files with the OpenFileDialog

    The last thing this tutorial goes over is how we can use the OpenFileDialog (the same one we used before) in order to let our users select multiple files. You will want to add a OpenFileDialog control from the toolbox to your form (like we did above). We named ours odlgFileNames. We will then hook up a button to show this dialog and to populate our list of files. You can see this in the button on the second tab of our sample project.

    image

    The code we use to allow our users to select multiple files is similar to what we did for the single file dialog with a few modifications.

    With odlgFileNames
    	.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Temp
    	.AddExtension = True
    	.CheckFileExists = True
    	.CheckPathExists = True
    	.DefaultExt = "txt"
    	.DereferenceLinks = True
    	.Filter = _
    		"Text files (*.txt)|*.txt|" & _
    		"All files|*.*"
     
    	.Multiselect = True
     
    	.RestoreDirectory = True
    	.ShowHelp = True
    	.ShowReadOnly = False
    	.Title = "Select a file"
    	.ValidateNames = True
     
    	If .ShowDialog() = Windows.Forms.DialogResult.OK Then
    		Dim strName As String
    		For Each strName In .FileNames
    		    lstFiles.Items.Add(strName)
    		Next
    	End If
    End With

    Most of this code is the same as what we did for the single file dialog. One of the main things to notice are that we set the Multiselect property to true (this allows the users to select more than one file). Another thing to notice is that after the user clicks the Ok button we loop through the FileNames property instead of the using the FileName property (like we did before). The FileNames property gives us a list of each file that the user selected. For this sample we simply add each of these file names to our list.


    Summary

    VB.NET makes it very easy for us to interact with the Microsoft Windows Common Dialogs. The nice part when using these Dialog Controls is that our end users will experience the dialogs they are used to when they interact with our program. Microsoft has also made it very easy for us Visual Basic developers to interface with this dialogs through the controls they provide.

    This tutorial went through a source sample that Microsoft produced to help us understand these Common Dialog Controls. You can download this source sample below:

    If you enjoyed this post, subscribe for updates (it's free)