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
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.
4 Comments
David
Thank you! What does RestoreDirectory = True do?
Sebastian
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/…
user2366842
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.
Teevus
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 UsingYou'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
PaulMag
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?
PaulMag
Nevermind. I found the answer to my question here: stackoverflow.com/questions/9646684/…