miércoles, 5 de octubre de 2011

Escritura y lectura de ficheros texto con StreamWriter y StreamReader

Aunque con FileStream se pueden leer y escribir ficheros de texto, estas operaciones se pueden realizar de forma más sencilla con el uso de lectores y escritores.

En los siguintes ejemplos se propone el uso de StreamWriter y StreamReader para escribir y leer de un fichero.

Como se puede ver, el proceso se reduce a tres pasos:
1 - Creación del lector o escritor.
2 - Leer o escribir.
3 - Cerrar el fichero.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CÓDIGO ESCRITURA EN FICHERO DE TEXTO
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    Private Sub bt_escribir_stream_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_escribir_stream.Click
        'se crea el stream
        'Dim fichero As New StreamWriter(RUTA FICHERO, AÑADIR, CODIFICACION)
        Dim fichero As New StreamWriter("C:\datos.txt", False, Encoding.Default)

        'Se escribe todo el contenido de un textbox en el fichero de texto
        fichero.Write(TextBox2.Text)

        'Se cierra el fichero
        fichero.Close()
    End Sub

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CÓDIGO LECTURA DE FICHERO DE TEXTO
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    Private Sub bt_leer_stream_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_leer_stream.Click
        'se crea el stream
        'Dim fichero As New StreamWriter(RUTA FICHERO, DETECTAR CODIFICACION)
        Dim fichero As New StreamReader("C:\datos.txt", True)

        'Se escribe todo el contenido de un textbox en el fichero de texto
        TextBox2.Text = fichero.ReadToEnd()

        'Se cierra el fichero
        fichero.Close()
    End Sub

No hay comentarios:

Publicar un comentario

Related Posts Plugin for WordPress, Blogger...