VB.NET OpenFileDialog RestoreDirectory for each dialog

By Steven Chang

November 22, 2010

openfiledialog, openfiledialog.initialdirectory, openfiledialog.restoredirectory, vb.net, vb.net 2005, vb.net openfiledialog

Here is a code snippet (VB.NET 2005) that demonstrates how you can implement a separate RestoreDirectory for each of the OpenFileDialog’s you have.

Basically what this does is it allows you to have multiple “Browse” dialogs that each remember their own last directory used.

I have added comments to Button1_Click code only as Button2_Click code is pretty much the same:
[code]Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
‘declare a new instance of OpenFileDialog
Dim diag As New OpenFileDialog

‘set initial directory to be shown to button’s tag value.
‘this is initially blank
diag.InitialDirectory = Button1.Tag

‘sets button’s tag to directory of the file selected
If diag.ShowDialog() = Windows.Forms.DialogResult.OK Then
Button1.Tag = System.IO.Path.GetDirectoryName(diag.FileName)
End If

‘output last directory shown on a label
Label1.Text = Button1.Tag
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim diag As New OpenFileDialog
diag.InitialDirectory = Button2.Tag
If diag.ShowDialog() = Windows.Forms.DialogResult.OK Then
Button2.Tag = System.IO.Path.GetDirectoryName(diag.FileName)
End If
Label2.Text = Button2.Tag
End Sub
End Class[/code]
Now, assuming that you will be putting a button to show the openfilediaglog, and assuming you will have a button (or some kind of control) for each of the openfiledialog, we can utilize the button’s or control’s .Tag property to store the directory last shown.

You may download the demo project to see this in action:
OpenFileDialog InitialDirectory Demo

Steven Chang

About the author

The roles I play: Leader, Husband, Dad, Son, Brother, Friend, Programmer, Investor, Trader, Marketer, Student, Teacher, Influencer.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Direct Your Visitors to a Clear Action at the Bottom of the Page

>