Permitir al usuario escoger un fichero para abrirlo

1988 vistas

El componente System.Windows.Form.OpenFileDialog permite al usuario escoger interactivamente un fichero.

Veamos un ejemplo que abre un fichero y lo lee poniendo su contenido en un RichTextBox.




vbnet
  1. Private Sub Button2_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
  2.  
  3.     ' TÃtulo
  4.     openFileDialog1.Title = "Cargar";
  5.     ' Extensión por defecto
  6.     openFileDialog1.DefaultExt = "txt";
  7.     ' Filtro sobre los ficheros
  8.     openFileDialog1.Filter = "Ficheros de texto (*.txt)|*.txt|Todos los ficheros (*.*)|*.*";
  9.     openFileDialog1.FilterIndex = 1;
  10.     ' abrimos cuadro de diálogo OpenFile
  11.     If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
  12.         ' vaciamos el TextBox
  13.         RichTextBox1.Text = String.Empty
  14.         ' abrimos el fichero seleccionado
  15.         ' su nombre está en openFileDialog1.FileName
  16.         Dim sr As StreamReader = New StreamReader(OpenFileDialog1.OpenFile, Encoding.Default)
  17.         Try
  18.             Dim data As String = sr.ReadLine
  19.             While Not (data Is Nothing)
  20.                 RichTextBox1.AppendText(data + _
  21.                                         Convert.ToChar(13) + _
  22.                                         Convert.ToChar(10))
  23.                 data = sr.ReadLine()
  24.             End While
  25.         Finally
  26.             If Not (sr Is Nothing) Then
  27.                 sr.Close()
  28.             End If
  29.         End Try
  30.     End If
  31.  
  32. End Sub