Leer y escribir en un fichero texto
Artículo por Club Developers · 11 May 2006
2408 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
Imports System.IO Sub FichierTexte(ByVal nombreFichero As String) Dim sr As StreamReader Dim sw As StreamWriter Dim sLine As String Try If Not File.Exists(nombreFichero) Then ' El fichero no existe. Lo creammos sw = New StreamWriter(nombreFichero) sw.WriteLine("Buenos días. DÃa {0} a las {1} ", DateTime.Now.ToLongDateString, DateTime.Now.ToLongTimeString) sw = Nothing ' Nota: podemos usar sw = File.AppendText(nombreFichero) para añadir texto a un fichero existente End If ' Abrimos fichero y lo leemos para mostrar su contenido en la cónsola sr = New StreamReader(nombreFichero) Console.WriteLine("Inicio fichero") sLine = sr.ReadLine() While Not sLine Is Nothing Console.WriteLine(sLine) sLine = sr.ReadLine() End While Console.WriteLine("Fin de fichero") Finally ' cerramos streamreader ' cerramos streamwriter End Try End Sub


