Table + SetOfTables + files C# Exercise - C# Programming Course

 Exercise

Table + SetOfTables + files

 Objetive

Expand the exercise (tables + array + files) by creating three classes: Table, SetOfTables, and a test program. The SetOfTables class should contain an array of tables, as well as two methods to dump all data from the array into a binary file and restore data from the file.

 Example Code

// Importing necessary namespaces
using System; // To use general .NET functionalities
using System.IO; // To perform file I/O operations

// Define a class to represent a single Table
class Table
{
    public string Name { get; set; } // Name of the table
    public string Description { get; set; } // Description of the table
    public int[] Data { get; set; } // Array to store table data

    // Constructor to initialize a new Table with a name, description, and data
    public Table(string name, string description, int[] data)
    {
        Name = name; // Assign name to the table
        Description = description; // Assign description to the table
        Data = data; // Assign the array of data to the table
    }

    // Method to dump the table's data into a binary file
    public void DumpToBinaryFile(string fileName)
    {
        try
        {
            // Open a new binary file for writing
            using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
            {
                // Write the table name to the file
                writer.Write(Name);
                // Write the table description to the file
                writer.Write(Description);
                // Write the size of the data array
                writer.Write(Data.Length);

                // Write each element of the data array to the file
                foreach (var item in Data)
                {
                    writer.Write(item); // Write individual elements of the data array
                }
            }

            // Notify that the data has been written successfully
            Console.WriteLine("Data dumped successfully to the binary file.");
        }
        catch (Exception ex)
        {
            // Display error message if any exception occurs
            Console.WriteLine($"Error writing to binary file: {ex.Message}");
        }
    }

    // Method to restore the table's data from a binary file
    public static Table RestoreFromBinaryFile(string fileName)
    {
        try
        {
            // Open the binary file for reading
            using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
            {
                // Read the table name
                string name = reader.ReadString();
                // Read the table description
                string description = reader.ReadString();
                // Read the size of the data array
                int length = reader.ReadInt32();

                // Initialize an array to hold the data
                int[] data = new int[length];

                // Read the data array from the file
                for (int i = 0; i < length; i++)
                {
                    data[i] = reader.ReadInt32(); // Read each integer from the file
                }

                // Return a new Table object with the restored data
                return new Table(name, description, data);
            }
        }
        catch (Exception ex)
        {
            // Display error message if any exception occurs
            Console.WriteLine($"Error reading from binary file: {ex.Message}");
            return null;
        }
    }
}

// Define a class to represent a collection of multiple Tables
class SetOfTables
{
    public Table[] Tables { get; set; } // Array to store multiple Table objects

    // Constructor to initialize a SetOfTables with an array of Table objects
    public SetOfTables(Table[] tables)
    {
        Tables = tables; // Assign the array of tables to the SetOfTables
    }

    // Method to dump all tables' data into a binary file
    public void DumpAllToBinaryFile(string fileName)
    {
        try
        {
            // Open a new binary file for writing
            using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
            {
                // Write the number of tables in the set
                writer.Write(Tables.Length);

                // Write each table's data to the file
                foreach (var table in Tables)
                {
                    // Dump each table's data to the binary file
                    table.DumpToBinaryFile(fileName); // Reusing Table's DumpToBinaryFile method
                }
            }

            // Notify that all tables' data has been written successfully
            Console.WriteLine("All table data dumped successfully to the binary file.");
        }
        catch (Exception ex)
        {
            // Display error message if any exception occurs
            Console.WriteLine($"Error writing to binary file: {ex.Message}");
        }
    }

    // Method to restore all tables' data from a binary file
    public static SetOfTables RestoreAllFromBinaryFile(string fileName)
    {
        try
        {
            // Open the binary file for reading
            using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
            {
                // Read the number of tables in the set
                int numberOfTables = reader.ReadInt32();

                // Initialize an array to hold the restored tables
                Table[] tables = new Table[numberOfTables];

                // Read each table's data from the binary file
                for (int i = 0; i < numberOfTables; i++)
                {
                    // Restore each table's data
                    tables[i] = Table.RestoreFromBinaryFile(fileName); // Reusing Table's RestoreFromBinaryFile method
                }

                // Return a new SetOfTables object with the restored tables
                return new SetOfTables(tables);
            }
        }
        catch (Exception ex)
        {
            // Display error message if any exception occurs
            Console.WriteLine($"Error reading from binary file: {ex.Message}");
            return null;
        }
    }
}

// Main class to demonstrate the SetOfTables functionality
class Program
{
    static void Main(string[] args)
    {
        // Example data to be used in the table
        int[] tableData1 = new int[] { 1, 2, 3, 4, 5 };
        int[] tableData2 = new int[] { 6, 7, 8, 9, 10 };

        // Create a few table instances
        Table table1 = new Table("Table1", "First Table Description", tableData1);
        Table table2 = new Table("Table2", "Second Table Description", tableData2);

        // Add tables to a SetOfTables collection
        SetOfTables setOfTables = new SetOfTables(new Table[] { table1, table2 });

        // Dump all tables' data to a binary file
        setOfTables.DumpAllToBinaryFile("allTablesData.bin");

        // Restore all tables' data from the binary file
        SetOfTables restoredSet = SetOfTables.RestoreAllFromBinaryFile("allTablesData.bin");

        // Check if the SetOfTables has been restored successfully
        if (restoredSet != null)
        {
            // Display the restored tables' data
            foreach (var restoredTable in restoredSet.Tables)
            {
                Console.WriteLine($"Restored Table Name: {restoredTable.Name}");
                Console.WriteLine($"Restored Table Description: {restoredTable.Description}");
                Console.WriteLine("Restored Data:");
                foreach (var item in restoredTable.Data)
                {
                    Console.Write(item + " "); // Display each item from the restored data array
                }
                Console.WriteLine(); // Add a newline between tables
            }
        }
    }
}

Juan A. Ripoll - Programming Tutorials and Courses © 2025 All rights reserved.  Legal Conditions.