Software Development optimize

Let users pick a file to open via OpenFileDialog in VB.NET


Whenever you need to allow a user to open a particular file without forcing the user to type the full path and file name, you can use the OpenFileDialog class. OpenFileDialog has a number of properties and methods that make it a flexible way to get users to pick a file. In this tip, I present an example that shows how you can use OpenFileDialog in VB.NET.

Put OpenFileDialog to use

It's very easy to use the OpenFileDialog class, which you will find under the Dialogs section of the toolbox. To add the control to your form, double-click it, and the component will appear below the form as in Figure A. Figure A

Figure A

For my example, I will also add a textbox and a command button to the form. To do so, change the text property of the command button to Open File and add the following code to the button's click event and to the FileOK event of the OpenFileDialog box:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        OpenFileDialog1.Title = "Please Select a File"

        OpenFileDialog1.InitialDirectory = "C:temp"

        OpenFileDialog1.ShowDialog()

    End Sub

    Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk

        Dim strm As System.IO.Stream

        strm = OpenFileDialog1.OpenFile()

        TextBox1.Text = OpenFileDialog1.FileName.ToString()

        If Not (strm Is Nothing) Then

        'insert code to read the file data

            strm.Close()

            MessageBox.Show("file closed")

        End If

    End Sub
Press [F5] to debug, and your form will look like Figure B. Figure B

Figure B

Click the Command button to open the File Open dialog box, as in Figure C. Figure C

Figure C

Once you select the file and click Open, the dialog box closes, and the full path of the file appears with the file name in the textbox. See Figure D. Figure D

Figure D

Notes about the example

I begin by setting the Title property of the OpenFileDialog box. Then, I set the initial directory that will open the first time the dialog box opens up. (The user can change it to any directory in run time.) I open the OpenFileDialog1 by using its ShowDialog method. After the user selects the file, I set the Text property of the textbox control to the file name selected in the OpenFileDialog with the help of the OpenFileDialog's FileName property. I open the file that the user selected and then close it.

You can use the functionality provided here to open the selected file or to store the name of the file that was selected, depending on the purpose of your particular application.

Irina Medvinskaya has been involved in technology since 1996. She has an MBA from Pace University and works as a project manager at Citigroup.

----------------------------------------------------------------------------------------

Get Visual Basic tips in your inbox

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically subscribe today!

14 comments
Udoya
Udoya

thanks! how about if I want to read the selected file from the location

Tokinabo
Tokinabo

Because I'm new in programming, this simple open file dialog example has been very usefull to me. Thanks a lot. :-)

spritchard
spritchard

so If I was to use a seprate button to access the file in the text box to stream write its contents to aother file.txt?

barerunner79
barerunner79

when i use your code for the openFileDialog the window comes up for the user to choose a file but after "OK" is clicked the windows close and the file does not open. i don't understand what i'm doing wrong. i'm very new to vb.net. please help!

prsureshbe
prsureshbe

how to copy a file or text in vb.net

franzvargas
franzvargas

waha if I want just file name with no extension? original path : c:\folder1\file.txt i need "file" only

rapp000
rapp000

and also the OpenFileDialog has other userful properties such as the filter property wich allows to open a file in an specific format, i use it very often when i work with xml files.

Justin James
Justin James

Good article, I like to use it a little bit different since the ShowDialog() method returns the value. I usually use: If dlgOpenFile.ShowDialog = DialogResult.OK Just because I tend to reuse dialog boxes, so handling the OK button could have disastrous results. :) J.Ja

elitecobra
elitecobra

The main purpose of the OpenFileDialog is to select a file and get the filename and path of the file the user selected. You can then do what it is you wanted to do with the file. If you want to actually execute/open the file that the user selects, then try the code below... ---------------------- If OpenFileDialog.ShowDialog() = DialogResult.OK Then Process.Start(OpenFileDialog.FileName) End If ---------------------- You can also put the Process.Start(OpenFileDialog.FileName) code in the OpenFileDialog_FileOK event. ---------------------- Private Sub OpenFileDialog_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog.FileOk Process.Start(OpenFileDialog.FileName) End Sub ---------------------- That event is fired if the user selects a filename. IF the user cancels or whatnot, then the _FileOK event will not fire. Anyways, hopefully you understand how the OpenFileDialog works and what its main purpose is. Jason

Tony Hopkinson
Tony Hopkinson

with the filesystem. Most use ones are File and Path in System.IO Import / use it. File. wait for good old intellisense to pop up and you get a whole stick of useful methods.

Justin James
Justin James

Look at the documentation for the System.File.IO namespace. It has everything you need for filename manipulation. J.Ja

elitecobra
elitecobra

Below is a small example of using the filter property. OpenDialog1.Filter = "MP3 Files(*.mp3)|*.mp3|All Files (*.*)|*.*" That will show the dialog with only MP3 files being visible or select the All Files combo item in the dialog to view them all. Either way its just a simple example. :) Jason http://www.vbcodesource.org