Leer y escribir en un fichero texto

2079 vistas

Veamos cómo hacerlo mediante un ejemplo en el que, si el fichero no existe, lo abriremos, llenaremos y mostraremos su contenido por pantalla. Para ello vamos a usar la clase System.IO.StreamReader para la lectura y System.IO.StreamWriter para la escritura.



csharp
  1. using System;
  2. using System.IO;
  3.  
  4. void FicheroTexto(string nombreFichero)
  5. {
  6.   StreamReader sr = null;
  7.   StreamWriter sw = null;
  8.   string line;
  9.   try
  10.   {
  11.     if (! File.Exists(nombreFichero))
  12.     {
  13.       // El fichero no existe. Lo creammos
  14.       sw = new StreamWriter(nombreFichero);
  15.       sw.WriteLine("Buenos días. DÃa {0} a las {1} ", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString());
  16.       sw.Close();
  17.       sw = null;
  18.       // Nota: podemos usar sw = File.AppendText(nombreFichero) para añadir
  19.       //      texto a un fichero existente
  20.     }
  21.     // Abrimos fichero y lo leemos para mostrar su contenido en pantalla
  22.     sr = new StreamReader(nombreFichero);
  23.     Console.WriteLine("Inicio fichero");
  24.     line = sr.ReadLine();
  25.     while (line != null)
  26.     {
  27.       Console.WriteLine(line);
  28.       line = sr.ReadLine();
  29.     }
  30.     Console.WriteLine("Fin de fichero");
  31.   }
  32.   finally
  33.   {
  34.     // cerramos streamreader
  35.     if (sr != null) sr.Close();
  36.     // cerramos streamwriter
  37.     if (sw != null) sw.Close();
  38.   }
  39. }