miércoles, 11 de junio de 2014

El Demo del Día: Leer y Escribir Archivos de Texto usando DataTable

Leer y Escribir Archivos de Texto usando DataTable

Requerimiento
Se desea leer un archivo con registros separador por un carácter, por ejemplo por comas, punto y coma o por el símbolo "|".
Luego el usuario podrá modificar los registros existentes y al final debería grabar en el mismo archivo o si desea en otro archivo todo los registros.

Solución
Una alternativa sería leer el archivo y almacenarlo en un DataTable de ADO .NET (aunque no es lo mejor), luego lo enlazamos a una grilla, en este caso el control DataGridView de WinForms y luego podemos grabar nuevamente el contenido del DataTable a un archivo de texto.

Paso 1: Función Genérica para Leer un Archivo de Texto en un DataTable
        public static DataTable TextoATabla(string archivo, char separador)
        {
            DataTable tabla = new DataTable();
            if (File.Exists(archivo))
            {
                using (StreamReader sr = new StreamReader(archivo))
                {
                    string[] cabeceras = sr.ReadLine().Split(separador);
                    if (cabeceras != null && cabeceras.Length > 0)
                    {
                        for (int i = 0; i < cabeceras.Length; i++)
                        {
                            tabla.Columns.Add(cabeceras[i], Type.GetType("System.String"));
                        }
                        DataRow fila = null;
                        string[] campos = null;
                        while (!sr.EndOfStream)
                        {
                            fila = tabla.NewRow();
                            campos = sr.ReadLine().Split(separador);
                            if (campos != null && campos.Length > 0)
                            {
                                for (int i = 0; i < campos.Length; i++)
                                {
                                    fila[i] = campos[i];
                                }                              
                            }
                            tabla.Rows.Add(fila);
                        }
                    }
                }
            }
            return (tabla);
        }

Paso 2: Función Genérica para Crear un Archivo de Texto desde un DataTable
        public static void TablaATexto(DataTable tabla, string archivo,char separador)
        {
            using(FileStream fs = new FileStream(archivo, FileMode.Create, FileAccess.Write, 
                    FileShare.Write))
            {
                using(StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                {
                    for(int i = 0;i< tabla.Columns.Count;i++)
                    {
                        sw.Write(tabla.Columns[i].ColumnName);
                        if(i<tabla.Columns.Count - 1) sw.Write(separador);
                    }
                    sw.WriteLine();
                    for(int j = 0;j< tabla.Rows.Count;j++)
                    {
                        for(int i = 0;i< tabla.Columns.Count;i++)
                        {
                            sw.Write(tabla.Rows[j][i].ToString());
                            if(i<tabla.Columns.Count - 1) sw.Write(separador);
                        }
                        sw.WriteLine();
                    }
                }
            }
        }
Nota: Ambas funciones usan el Namespace System.IO y System.Data

Paso 3: Archivo de Texto separados por un caractér (csv)
ProductID,ProductName,SupplierID,CategoryID,UnitPrice,UnitsInStock
1,Chai,2,1,10.0000,76
2,Chang,7,4,3.0000,22
3,Chicha,10,1,10.0000,35
4,Chef Anton's Cajun Seasoning,2,2,22.0000,80
5,Chef Anton's Gumbo Mix,2,2,21.3500,31
6,Grandma's Boysenberry Spread,2,3,25.0000,50
7,Uncle Bob's Organic Dried Pears,3,7,30.0000,98
8,Northwoods Cranberry Sauce,3,2,40.0000,99
9,Mishi Kobe Niku,4,6,97.0000,96
10,Ikura,4,8,31.0000,93
..............................................................................

Paso 4: Crear un  Formulario con una Grilla que pueda usar las 2 Funciones
Asumiendo que las 2 funciones estáticas fueron creadas en una clase llamada "ucTextoTabla" y hemos creado un formulario llamado: "frmPrueba" conteniendo un control DataGridView llamado: "dgvTexto" y 2 botones llamados: "btnLeerArchivoTxt" y "btnCrearArchivoTxt", tal como se muestra en la siguiente imagen:


Escribir el siguiente código en el formulario:
    public partial class frmPrueba : Form
    {
        DataTable tabla;

        public frmPrueba()
        {
            InitializeComponent();
        }

        private void btnLeerArchivoTxt_Click(object sender, EventArgs e)
        {
            tabla = ucTextoTabla.TextoATabla("Productos.txt", ',');
            dgvTexto.DataSource = tabla;
        }

        private void btnCrearArchivoTxt_Click(object sender, EventArgs e)
        {
            ucTextoTabla.TablaATexto(tabla,"Productos2.txt", ',');
            MessageBox.Show("Archivo de Texto creado");
        }
    }

Paso 5: Ejecutar la aplicación y Probar
Para ejecutar la aplicación se tiene que tener el archivo: "Productos.txt" en la carpeta bin/debug donde corre la aplicación con los datos descritos en el paso 3.
Primero dar clic al primer botón: "Leer Archivo Txt" y se cargarán los datos de los productos desde el archivo; luego ingresar nuevos registros, modificar los existentes y finalmente dar clic al botón "Crear Archivo Txt" y observar que se ha creado en la carpeta bin/debug el archivo "Productos2.txt".


Espero les guste el primer Demo y este fue un pedido. Ya saben que cualquier solicitud o requerimiento es bienvenida. No se olviden sus comentarios.

Descarga:
Demo01_LeerCrearArchivoTexto



El Libro del Día: .NET Domain-Driven Design with C#

El Libro del Día: 2014-06-11

Titulo: .NET Domain-Driven Design with C#
Autor: Tim McCarthy
Editorial: Wrox
Nro Paginas: 435

Capítulos:
Chapter 1: Introducing the Project: The SmartCA Application
Chapter 2: Designing the Layered Architecture
Chapter 3: Managing Projects
Chapter 4: Companies and Contacts
Chapter 5: Submittal Transmittals
Chapter 6: Requests for Information
Chapter 7: Proposal Requests
Chapter 8: Change Orders
Chapter 9: Construction Change Directives
Chapter 10: Synchronizing With the Server
Chapter 11: The Client Membership System

Descarga:
NET_DomainDrivenDesign_C#