DotNetWebTutor.com                                                    Link to Us

OpenFileDialog
Allows you to prompt your user to open an existing file
Properties:

  • Filter
    • Allows you to show only the files with certain extensions
      • Ex:
      • openFileDialog1.Filter=”*.txt|*.htm|*.html”
  • FilterIndex
    • Lets you set a default filetype from your filter
      • Ex:
      • OpenFileDialog1.FilterIndex(2)
    • Sets the default to .html
  • FileName
    • Shows the string in the filename combobox
      • Ex:
      • OpenFileDialog1.Filename=”default.html”
  • InitialDirectory
    • Sets the directory the dialogbox will start in
      • Ex:
      • OpenFileDialog1.InitialDirectoy=”C:\myfiles”

SaveFileDialog
Allows the user to pick where they will save their file

  • DefaultExt
    • Add a default extension to your files
      • Ex:
      • SaveFileDialog1.DefaultExt=”html”
  • Filter
    • Allows you to show only the files with certain extensions
      • Ex:
      • SaveFileDialog1.Filter=”*.txt|*.htm|*.html”
  • FilterIndex
    • Lets you set a default filetype from your filter
      • Ex:
      • SaveFileDialog1.FilterIndex(2)
    • Sets the default to .html
  • FileName
    • Shows the string in the filename combobox
      • Ex:
      • SaveFileDialog1.Filename=”default.html”
  • InitialDirectory
    • Sets the directory the dialogbox will start in
      • Ex:
      • SaveFileDialog1.InitialDirectoy=”C:\myfiles”

 

opening a text file in visual basic
Opening a text File

  • Create a new project
  • Drag an openfiledialog control to the form
  • Drag a label, textbox and button to the form
  • Name the label lblFilename
  • Set the textbox to multiline
  • Change the text of the button to Open a file
  • Name the label lblFilename

open a file

  • Drag a openFileDialog to the form
  • Set the filter to:

*.html|*.htm

  • Set the defaultext to html
  • Double-click the button
  • and add this code at the top of the page:

Imports system.io

Add this code to the button_click event
Dim myContent As String
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim reader As New StreamReader(OpenFileDialog1.FileName)
myContent = reader.ReadToEnd()
reader.Close()
lblFilename.Text = OpenFileDialog1.FileName.ToString()
TextBox1.Text = myContent
End If

Saving a file

  • Add another button and change the text to Save File
  • Drag a saveFileDialog to the form
  • Set the defaultext to html
  • Set the filter property to .html
  • Add this code to the button:

If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim writer As New StreamWriter(SaveFileDialog1.FileName)
writer.Write(TextBox1.Text)
writer.Close()
End If

  • Add this code to the end of the openButton code:

SaveFileDialog1.FileName = OpenFileDialog1.FileName.ToString()

opening a text file in vb