DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Mastering C# Fundamentals :Exploring File Handling

Before diving deep into file handling in this article, let’s kick things off with a practical demo. We’re using our existing knowledge to create a more complete and fully functional application, adding file handling support step by step. Let’s start with the current state of our application.

Running the Application: A Sneak Peek

The application we're building revolves around managing a list of books, allowing us to register, view, and eventually save and load books from files. For now, we have a menu to:

  1. Register books
  2. View all books
  3. Save books to a file (placeholder)
  4. Load books from a file (placeholder)
  5. Quit the application

Options 1 and 2 will be implemented in this step-by-step guide, while 3 and 4 are placeholders for future parts. Let’s begin by setting up the application.

Step-by-Step Code Walkthrough

The application code is split across three main files: Program.cs, Utilities.cs, and Book.cs. Let’s go through each component step by step with code snippets.

Step 1: Setting Up the Program Class

Program.cs serves as the entry point of our application. Here, we define our main loop and allow the user to navigate through the different options.

using System;
using System.Collections.Generic;

namespace BookManagementApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Book> books = new List<Book>(); // List to store registered books.
            Utilities.CheckForExistingBookFile(); // Placeholder to check if a file with book data exists.

            bool running = true;

            // Main menu loop
            do
            {
                Console.Clear(); // Clear the console for a clean look.
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Book Management Application");
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine($"Books Loaded: {books.Count}");
                Console.WriteLine("\nMenu:");
                Console.WriteLine("1. Register a Book");
                Console.WriteLine("2. View All Books");
                Console.WriteLine("3. Save Books to File (TODO)");
                Console.WriteLine("4. Load Books from File (TODO)");
                Console.WriteLine("9. Quit");

                Console.Write("\nSelect an option: ");
                string userSelection = Console.ReadLine();

                switch (userSelection)
                {
                    case "1":
                        Utilities.RegisterBook(books); // Register a new book.
                        break;
                    case "2":
                        Utilities.ViewBooks(books); // View all registered books.
                        break;
                    case "9":
                        running = false; // Exit the application.
                        break;
                    default:
                        Console.WriteLine("Invalid selection, please try again.");
                        break;
                }

                if (running)
                {
                    Console.WriteLine("\nPress Enter to continue...");
                    Console.ReadLine();
                }

            } while (running);

            Console.WriteLine("Thanks for using the Book Management Application!");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
Explanation
  • Tracking Books: We use a List<Book> to store registered books dynamically.
  • Menu System: We create a do...while loop to keep the menu running until the user chooses to quit (by entering 9). This loop ensures the menu is printed at least once, and a switch statement is used to determine the next action based on user input.

Step 2: Creating the Utilities Class

The Utilities.cs file contains helper methods like registering books and viewing the list of books. Let's implement the methods for handling options 1 and 2.

using System;
using System.Collections.Generic;

namespace BookManagementApp
{
    public static class Utilities
    {
        public static void CheckForExistingBookFile()
        {
            // Placeholder for checking if a book data file exists.
            Console.WriteLine("Checking for existing book file (not implemented yet)...");
        }

        public static void RegisterBook(List<Book> books)
        {
            Console.WriteLine("\nRegister a New Book:");

            // Collecting book details from the user
            Console.Write("Enter Title: ");
            string title = Console.ReadLine();

            Console.Write("Enter Author: ");
            string author = Console.ReadLine();

            Console.Write("Enter Genre (e.g., Fiction, Mystery): ");
            string genre = Console.ReadLine();

            Console.Write("Enter Publication Date (yyyy-mm-dd): ");
            DateTime publicationDate;
            while (!DateTime.TryParse(Console.ReadLine(), out publicationDate))
            {
                Console.Write("Invalid date format. Enter Publication Date (yyyy-mm-dd): ");
            }

            // Creating a new Book instance and adding it to the list
            Book newBook = new Book(title, author, genre, publicationDate);
            books.Add(newBook);

            Console.WriteLine("Book registered successfully!");
        }

        public static void ViewBooks(List<Book> books)
        {
            Console.WriteLine("\nList of Registered Books:");

            if (books.Count == 0)
            {
                Console.WriteLine("No books registered.");
            }
            else
            {
                foreach (var book in books)
                {
                    book.DisplayBookDetails(); // Display each book's details.
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
Explanation
  • RegisterBook(): This method handles user input for book details (title, author, genre, publication date) and creates a new book instance, adding it to the list.
  • ViewBooks(): This method loops through all books in the list and displays their details. If no books are registered, it informs the user.

Step 3: Defining the Book Class

We also need a class to represent each book. Let’s create the Book.cs file, which includes properties for the book details and a method to display those details.

using System;

namespace BookManagementApp
{
    public class Book
    {
        public string Title { get; set; }
        public string Author { get; set; }
        public string Genre { get; set; }
        public DateTime PublicationDate { get; set; }

        public Book(string title, string author, string genre, DateTime publicationDate)
        {
            Title = title;
            Author = author;
            Genre = genre;
            PublicationDate = publicationDate;
        }

        public void DisplayBookDetails()
        {
            Console.WriteLine($"Title: {Title}, Author: {Author}, Genre: {Genre}, Publication Date: {PublicationDate.ToShortDateString()}");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
Explanation
  • Book Class: This class contains properties for the book's title, author, genre, and publication date. The DisplayBookDetails() method is used to print all the details of a book in a clean, formatted manner.

Testing Options 1 and 2

Now that we’ve implemented options 1 and 2, let’s walk through how they work in our console application.

  1. Registering a Book:

    • When you select option 1 from the menu, you are prompted to enter details for a book: title, author, genre, and publication date.
    • After entering the information, the application confirms that the book has been registered.
  2. Viewing All Books:

    • When you select option 2, the application lists all the registered books.
    • If no books have been registered, it informs you that there are no books available.

What’s Next: Adding File Handling Support

The current version of the application allows us to register and view books in memory. However, this data is lost when the application is closed. To solve this, we will add the ability to:

  1. Save Book Data to a File: Implement a method to save book data to a file for persistence.
  2. Load Book Data from a File: Implement a method to load book data back into memory when the application starts.

These features will make our application more practical and robust by allowing us to store and retrieve data even after closing the application.

Conclusion

In this article, we have walked through implementing options 1 and 2 of our book management application step by step, complete with code snippets. We now have a working application that allows us to register and view books. The next part of the series will focus on adding file handling capabilities to make our application more persistent.

Stay tuned for the next steps, where we’ll extend this application by adding save and load functionality, turning our in-memory application into one that can truly save and retrieve data!

Top comments (0)