Leer y escribir en un fichero texto

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



vbnet
  1. Imports System.IO
  2.  
  3. Sub FichierTexte(ByVal nombreFichero As String)
  4.     Dim sr As StreamReader
  5.     Dim sw As StreamWriter
  6.     Dim sLine As String
  7.     Try
  8.         If Not File.Exists(nombreFichero) Then
  9.             ' El fichero no existe. Lo creammos
  10.             sw = New StreamWriter(nombreFichero)
  11.             sw.WriteLine("Buenos días. DÃa {0} a las {1} ", DateTime.Now.ToLongDateString, DateTime.Now.ToLongTimeString)
  12.             sw.Close()
  13.             sw = Nothing
  14.             ' Nota: podemos usar sw = File.AppendText(nombreFichero) para añadir texto a un fichero existente
  15.         End If
  16.         ' Abrimos fichero y lo leemos para mostrar su contenido en la cónsola
  17.         sr = New StreamReader(nombreFichero)
  18.         Console.WriteLine("Inicio fichero")
  19.         sLine = sr.ReadLine()
  20.         While Not sLine Is Nothing
  21.             Console.WriteLine(sLine)
  22.             sLine = sr.ReadLine()
  23.         End While
  24.         Console.WriteLine("Fin de fichero")
  25.     Finally
  26.         ' cerramos streamreader
  27.         If Not IsNothing(sr) Then sr.Close()
  28.         ' cerramos streamwriter
  29.         If Not IsNothing(sw) Then sw.Close()
  30.     End Try
  31. End Sub