Permitir al usuario escoger un fichero para abrirlo

2099 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.



csharp
  1. private void button2_Click(object sender, System.EventArgs e)
  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(this) == DialogResult.OK)
  12.     {
  13.         // vaciamos el TextBox
  14.         richTextBox1.Text = string.Empty;
  15.         // abrimos el fichero seleccionado
  16.         // su nombre está en openFileDialog1.FileName
  17.         StreamReader sr = new StreamReader(openFileDialog1.OpenFile(), Encoding.Default);
  18.         try
  19.         {
  20.             string data = sr.ReadLine();
  21.             while ( data != null)
  22.             {
  23.                 richTextBox1.AppendText(data + "\r\n");
  24.                 data = sr.ReadLine();
  25.             }
  26.         }
  27.         finally
  28.         {
  29.           if (sr!=null)
  30.                 sr.Close();
  31.         }
  32.     }
  33. }