Table + Setoftables + Files - C# Programming Exercise

In this exercise, you are asked to expand the previous exercise (tables + array + files) by creating three new classes: Table, SetOfTables, and a test program. The SetOfTables class should contain an array of Table objects, as well as two methods. The first of these methods will handle dumping all the data from the array of tables into a binary file, while the second method will restore the data from that binary file back into the original array. This exercise will help you understand how to organize data into classes and how to manage data persistence using binary files. Additionally, you will learn how to work with arrays of objects and handle file I/O operations in a more complex context.

Through this exercise, you will practice manipulating data in C# using object-oriented principles and efficiently storing information in binary files. These types of operations are essential in applications where a significant amount of data needs to be stored and retrieved in an efficient and structured manner.

 Category

Object Persistence

 Exercise

Table + Setoftables + Files

 Objective

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.

 Write Your C# Exercise

// 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
            }
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of Object Persistence

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Insects + persistence

    In this exercise, you need to create a new version of the insects exercise where the data is persisted using some form of storage, such as a database or...

  •  Cities - persistence

    In this exercise, you need to create a new version of the cities database, using persistence to store its data instead of text files. The goal of this exercise...

  •  Table + array + files

    In this exercise, you are asked to expand the previous exercise (tables + array) by adding two new methods. The first of these methods should handle dumping the array...