32

In a VB.NET Windows Forms application how do I add the capability for someone to click a button or image and open a file browser to browse to a file and assign it's path to a variable so I can copy that file to another specific path?

2 Answers 2

58

You should use the OpenFileDialog class like this

Dim fd As OpenFileDialog = New OpenFileDialog() 
Dim strFileName As String

fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True

If fd.ShowDialog() = DialogResult.OK Then
   strFileName = fd.FileName
End If

Then you can use the File class.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! What does RestoreDirectory = True do?
if you open a dialog and choose a path, than you cancel the dialog. Next time you open the dialog, the first choosen path is shown again, if restoreDirectory is set to true. For detail information look at msdn.microsoft.com/en-us/library/…
Quite late to the party, but might also want to be aware of the Multiselect property, because as it stands, if someone uses this block of code, it would have some rather unexpected results if multiple files are selected.
OpenFileDialog implements IDisposable, so you should dispose it after you are finished. Easiest is to use the Using keyword Using fd As OpenFileDialog = New OpenFileDialog() ... End Using
13

You're looking for the OpenFileDialog class.

For example:

Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
    Using dialog As New OpenFileDialog
        If dialog.ShowDialog() <> DialogResult.OK Then Return
        File.Copy(dialog.FileName, newPath)
    End Using
End Sub

2 Comments

I just get ´'OpenFileDialog' is not defined´. I tried ´Imports System.Windows.Forms´, but it doesn't seem to exist. Every single tutorial on this seems to assume that OpenFileDialog should just be available by default, but it isn't for me. In Nuget packet manager in Visual Studio I find ´System.Windows.Forms.Ribbon35´ and ´System.Windows.Forms.Pictograms´, but not just ´System.Windows.Forms. What am I missing?
Nevermind. I found the answer to my question here: stackoverflow.com/questions/9646684/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.