Leyendo y escribiendo archivos de texto y binarios en C# .NET
Utilizar streams para la lectura y escritura de archivos de texto y binarios en .NET.

Fecha: 18/Ene/2005 (17/Ene/05)
Autor: Serge Valsse (svalsse@hotmail.com)

 


La lectura y escritura a un archivo son hechas usando un concepto genérico llamado stream. La idea detrás del stream existe hace tiempo, cuando los datos son pensados como una transferencia de un punto al otro como un flujo de datos. En el ambiente .NET usted puede encontrar muchas clases que representan este concepto que trabaja con archivos o con datos de memoria (ver la figura de abajo).


Figura 1. Clases del Framework .NET para el uso de Streams.



BufferedStream

Esta clase se utiliza para leer y para escribir a otro stream. Se utiliza por razones del performance, cuando el caché de los datos del archivo es utilizado por el sistema operativo subyacente.

El uso de streams para la lectura y escritura de archivo es directa pero lenta con bajo performance. Por esta razón la clase BufferedStream existe y es más eficiente. Puede ser utilizado por cualquier clase de stream. Para operaciones de archivo es posible utilizar FileStream, donde el buffering está ya incluido.

Leyendo desde un archivo usando BufferedStream

using System;
using System.Text;
using System.IO;

static void Main(string[] args)
{
    string path = "c:\\sample\\sample.xml";
    Stream instream = File.OpenRead(path);

    // crear buffer para abrir stream
    BufferedStream bufin = new BufferedStream(instream);
    byte[] bytes = new byte[128];

    // leer los primeros 128 bytes del archivo
    bufin.Read(bytes, 0, 128);
    Console.WriteLine("Allocated bytes: "+Encoding.ASCII.GetString(bytes));
}

Leyendo desde un archivo de texto

using System;
using System.IO;

static void Main(string[] args)
{
    string fileName = "temp.txt";
    FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    StreamReader reader = new StreamReader(stream);

    while (reader.Peek() > -1) Console.WriteLine(reader.ReadLine());
    reader.Close();
}

Escribiendo en un archive de texto

using System;
using System.IO;

static void Main(string[] args)
{
    string fileName = "temp.txt";
    FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
    StreamWriter writer = new StreamWriter(stream);

    writer.WriteLine("Esta es la primera línea del archivo.");
    writer.Close();
}

Creando un archivo y escribiendo en este

Este ejemplo usa el método CreateText() el cual crea un Nuevo archive y retorna un objeto StreamWriter que escribe a un archivo usando formato UTF-8.

using System;
using System.IO;

static void Main(string[] args)
{
    string fileName = "temp.txt";
    StreamWriter writer = File.CreateText(fileName);

    writer.WriteLine("Este es mi Nuevo archivo creado.");
    writer.Close();
}

Insertando texto en un archivo

using System;
using System.IO;

static void Main(string[] args)
{
    try
    {
        string fileName = "temp.txt";
        // esto inserta texto en un archivo existente, si el archivo no existe lo crea
        StreamWriter writer = File.AppendText(fileName);
        writer.WriteLine("Este es el texto adicionado.");
        writer.Close();
    }
    catch
    {
        Console.WriteLine("Error");
    }
}

Leyendo un archivo binario

using System;
using System.IO;

static void Main(string[] args)
{
    try
    {
        string fileName = "temp.txt";
        int letter = 0;
        FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        BinaryReader reader = new BinaryReader(stream);

        while (letter != -1)
        {
            letter = reader.Read();
            if (letter != -1) Console.Write((char)letter);
        }
        reader.Close();
        stream.Close();
    }
    catch
    {
        Console.WriteLine("Error");
    }
}

Escribiendo en un archivo binario

static void Main(string[] args)
{
    try
    {
        string fileName = "temp.txt";
        // data a ser guardada
        int[] data = {0, 1, 2, 3, 4, 5};
        FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Write);
        BinaryWriter writer = new BinaryWriter(stream);

        for(int i=0; i<data.Length; i++)
        {
            // números son guardados en formáto UTF-8 format (4 bytes)
            writer.Write(data[i]);
        }

        writer.Close();
        stream.Close();
    }
    catch
    {
        Console.WriteLine("Error");
}

Ver cambios en el file system

.NET Framework prove la calse System.IO.FileSystemWatcher la cual permite ver si hay cambios en el file system.

using System;
using System.IO;
class WatcherSample
{
    static void Main(string[] args)
    {
        // ver los cambios en el directorio de la aplicación y sobre todos los archivos
        FileSystemWatcher watcher = new FileSystemWatcher(System.Windows.Forms.Application.StartupPath, "*.*");

        // ver el nombre del archivo y tamaño cambiado
        watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size;
        watcher.Changed += new FileSystemEventHandler(OnChange);
        watcher.Created += new FileSystemEventHandler(OnChange);
        watcher.Deleted += new FileSystemEventHandler(OnChange);
        watcher.Renamed += new RenamedEventHandler(OnChange);
        watcher.EnableRaisingEvents = true;

        // espera por una tecla para terminar la aplicación
        Console.ReadLine();
    }
    private static void OnChange(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("File: {0} - change type: {1}", e.FullPath, e.ChangeType);
    }
    private static void OnChange(object sender, RenamedEventArgs e)
    {
        Console.WriteLine("File: {0} renamed to {1}", e.OldName, e.Name);
    }
}



Por favor no olvides calificar el artículo en la caja de PanoramaBox que se muestra al inicio de la página.

Serge Valsse
svalsse@hotmail.com


 


ir al índice