lunes, 5 de octubre de 2009

Trabajar con ficheros de Texto

Creamos una aplicación WindowsForms

En el Form1.VB escribimos Imports system.IO encima del Public Class Form1 (Esto importa la librería System.IO que es la que se usa para leer y escribir ficheros desde .Net)

Añadimos un textbox multilínea (miTexto) y un botón (btnCargar) al formulario y le añadimos el siguiente código al evento click:

Private Sub btnCargar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCargar.Click
If File.Exists("TextFile.txt") then 'Si el archivo existe lo abrimos en modo lectura
Dim reader As StreamReader = New StreamReader("TextFile.txt")
miTexto.Text = r.ReadToEnd() 'Añadimos el contenido del txt al textbox
reader.Close() 'Cerramos la conexión con el txt
Else
Dim writer as new StreamWriter("TextFile.txt") 'Si no existe lo creamos
writer.Close() 'Cerramos la conexión con el txt
End If
End Sub

Si queremos editar el fichero txt y luego guardar los cambios, creamos otro botón (btnGuardar) y le añadimos el siguiente código al evento click:

Private Sub btnGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGuardar.Click
Dim writer As StreamWriter = New StreamWriter("lista.txt") 'Abrimos el txt en modo escritura
writer.Write(miTexto.Text) 'Escribimos en el txt el contenido del textbox
writer.Close() 'Cerramos la conexión con el txt
End Sub

Para rematar la faena podemos crear un tercer botón (btnBorrar) y le añadimos el siguiente código al evento click:

Private Sub btnBorrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBorrar.Click
If File.Exists("TextFile.txt") 'Si el archivo existe lo borramos
File.Delete("TextFile.txt")
else 'Si no existe mostramos un mensaje de error
msgbox("El fichero no existe")
end if

Para nota: Lectura del fichero linea a línea

Dim ioLine as string ' Línea leida
Dim ioLines as string ' Concatenación de líneas
ioLine = ioFile.ReadLine
ioLines = ioLine
While not ioLine = "" OR Nothing
ioLine = ioFile.ReadLine
ioLines = ioLines & vbcrlf & ioLine
End While
MsgBox(ioLines) 'Podemos mostrar el contenido en un MsgBox o a un TextBox
ioFile.close()

1 comentario:

  1. Con Dim writer As StreamWriter = New StreamWriter("lista.txt") abrimos el txt en modo escritura pero al escribir machacamos el contenido si hacemos File.AppendText("lista.txt") al usar los métodos Write o WriteLine, añadiremos el nuevo texto al final.

    If (Not File.Exists("c:\test.txt")) Then
    st = File.CreateText("c:\test.txt")
    Else
    st = File.AppendText("c:\test.txt")
    End If
    st.WriteLine("Texto deseado")
    st.Close()

    ResponderEliminar