Tabla + matriz + archivos Ejercicio C# - Curso de Programación C# (C Sharp)

 Ejercicio

Tabla + matriz + archivos

 Objetivo

Expanda el ejercicio del 9 de enero (tablas + matriz), de modo que contenga dos nuevos métodos, volcar los datos de la matriz en un archivo binario y restaurar los datos del archivo.

 Código de Ejemplo

using System;
using System.IO;
namespace Tables
{
    class Table
    {
        protected int width, height;

        public Table(int tableWidth, int tableHeight)
        {
            width = tableWidth;
            height = tableHeight;
        }

        public void ShowData()
        {
            Console.WriteLine("Width: {0}, Height: {1}", width, height);
        }

        public void Save(string name)
        {
            BinaryWriter outputFile = new BinaryWriter(
            File.Open(name, FileMode.Create));
            outputFile.Write(height);
            outputFile.Write(width);
            outputFile.Close();
        }

        public void Load(string name)
        {
            BinaryReader inputFile = new BinaryReader(
            File.Open(name, FileMode.Open));
            height = inputFile.ReadInt32();
            width = inputFile.ReadInt32();
            inputFile.Close();
        }
    }
}

using System;
namespace Tables
{
    class TestTable
    {
        static void Main(string[] args)
        {
            Table[] tableList = new Table[10];
            Random random = new Random();

            for (int i = 0; i < tableList.Length - 1; i++)
            {
                tableList[i] = new Table(
                    random.Next(50, 201),
                    random.Next(50, 201));
            }
            tableList[0].Save("1.dat");
            tableList[9] = new Table(0, 0);
            tableList[9].Load("1.dat");

            for (int i = 0; i < tableList.Length; i++)
            {
                tableList[i].ShowData();
            }

            Console.ReadLine();
        }
    }
}

Juan A. Ripoll - Tutoriales y Cursos de Programacion© 2024 Todos los derechos reservados.  Condiciones legales.