Table + Array + Files - C# Programming Exercise

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 data into a binary file. The second method must be able to restore that data from the binary file back into the original array. This process involves writing the array data efficiently to a binary file and then reading that file to recover the information, allowing for data persistence. Through this exercise, you will learn how to work with binary file I/O operations, which is useful when you need to store data in a compact and fast manner. The approach of working with binary files will help you understand how to manage data efficiently in applications that require handling large volumes of information.

 Category

Object Persistence

 Exercise

Table + Array + Files

 Objective

Expand the exercise (tables + array) by adding two new methods to dump the data of the array into a binary file and restore the 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 the structure of the 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;
        }
    }
}

// Main class to demonstrate the Table and array functionality
class Program
{
    static void Main(string[] args)
    {
        // Example data to be used in the table
        int[] tableData = new int[] { 1, 2, 3, 4, 5 };

        // Create a new table instance
        Table table = new Table("Table1", "Example Table Description", tableData);

        // Dump the table data to a binary file
        table.DumpToBinaryFile("tableData.bin");

        // Restore the table data from the binary file
        Table restoredTable = Table.RestoreFromBinaryFile("tableData.bin");

        // Check if the table has been restored successfully
        if (restoredTable != null)
        {
            // Display the restored table data
            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
            }
        }
    }
}

 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#.

  •  Table + SetOfTables + files

    In this exercise, you are asked to expand the previous exercise (tables + array + files) by creating three new classes: Table, SetOfTab...

  •  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...