Friends Database, Using Files - C# Programming Exercise

This C# exercise aims to expand a friends database by allowing data to be loaded from a file at the beginning of each session and saved to a file when the session ends. If the file exists, the program should automatically load the data, ensuring that entries made during a session are available in the next one.

In this exercise, you need to implement functionality to read and write data to a file, making sure that user-entered information, such as friends' names and their details, persists between sessions. The challenge involves creating a simple persistence system where the database is effectively stored and retrieved from a file. This exercise is perfect for practicing file handling and data persistence in C#.

By completing this exercise, you will improve your skills in file management and in building systems that retain data between program executions.

 Category

File Management

 Exercise

Friends Database, Using Files

 Objective

Expand the "friends database", so that it loads data from file at the beginning of each session (if the file exists) and saves the data to file when the session ends. Therefore, the data entered in a session must be available for the next session.

 Write Your C# Exercise

// Importing necessary namespaces for file handling and basic C# functionalities
using System; // For basic Console operations
using System.IO; // For file handling
using System.Collections.Generic; // For using the List collection

public class Friend
{
    // Properties to store friend's details
    public string Name { get; set; } // Name of the friend
    public string PhoneNumber { get; set; } // Phone number of the friend
    public string Email { get; set; } // Email address of the friend

    // Constructor to initialize the friend's details
    public Friend(string name, string phoneNumber, string email)
    {
        Name = name;
        PhoneNumber = phoneNumber;
        Email = email;
    }

    // Method to return a string representation of the friend's data
    public override string ToString()
    {
        return $"{Name},{PhoneNumber},{Email}"; // Format the friend data to CSV (comma-separated)
    }

    // Static method to create a Friend object from a CSV formatted string
    public static Friend FromString(string str)
    {
        string[] parts = str.Split(','); // Split the string by commas
        return new Friend(parts[0], parts[1], parts[2]); // Return a new Friend object
    }
}

public class FriendsDatabase
{
    // List to store all friends
    private List friends;

    // File path to save and load friends data
    private string fileName;

    // Constructor that initializes the friends list and file name
    public FriendsDatabase(string fileName)
    {
        this.fileName = fileName;
        this.friends = new List();
        LoadFromFile(); // Attempt to load data from file at the start of the session
    }

    // Method to load friends from file if the file exists
    private void LoadFromFile()
    {
        if (File.Exists(fileName)) // Check if the file exists
        {
            string[] lines = File.ReadAllLines(fileName); // Read all lines from the file

            foreach (string line in lines)
            {
                if (!string.IsNullOrWhiteSpace(line)) // Skip empty lines
                {
                    friends.Add(Friend.FromString(line)); // Add each friend to the list
                }
            }
        }
    }

    // Method to save the current list of friends to the file
    public void SaveToFile()
    {
        using (StreamWriter writer = new StreamWriter(fileName))
        {
            foreach (var friend in friends)
            {
                writer.WriteLine(friend.ToString()); // Write each friend to the file
            }
        }
    }

    // Method to add a new friend to the database
    public void AddFriend(string name, string phoneNumber, string email)
    {
        friends.Add(new Friend(name, phoneNumber, email)); // Add the new friend to the list
    }

    // Method to display all friends in the database
    public void DisplayFriends()
    {
        if (friends.Count == 0)
        {
            Console.WriteLine("No friends to display."); // Notify if no friends are present
        }
        else
        {
            foreach (var friend in friends)
            {
                Console.WriteLine($"Name: {friend.Name}, Phone: {friend.PhoneNumber}, Email: {friend.Email}");
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        string fileName = "friendsDatabase.txt"; // Define the file name to save/load data

        FriendsDatabase database = new FriendsDatabase(fileName); // Initialize the database with the file name

        while (true)
        {
            // Display the menu options
            Console.WriteLine("\nFriends Database");
            Console.WriteLine("1. Add Friend");
            Console.WriteLine("2. Display All Friends");
            Console.WriteLine("3. Exit");
            Console.Write("Choose an option: ");
            string choice = Console.ReadLine(); // Read user input

            if (choice == "1")
            {
                // Ask for friend's details to add
                Console.Write("Enter friend's name: ");
                string name = Console.ReadLine();
                Console.Write("Enter phone number: ");
                string phone = Console.ReadLine();
                Console.Write("Enter email address: ");
                string email = Console.ReadLine();

                // Add the new friend to the database
                database.AddFriend(name, phone, email);
                Console.WriteLine("Friend added successfully.");
            }
            else if (choice == "2")
            {
                // Display all friends
                database.DisplayFriends();
            }
            else if (choice == "3")
            {
                // Save data to file before exiting
                database.SaveToFile();
                Console.WriteLine("Data saved. Exiting the program...");
                break; // Exit the program
            }
            else
            {
                Console.WriteLine("Invalid option. Please try again.");
            }
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

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

  •  Pascal to C# translator

    This C# exercise involves creating a basic Pascal to C# translator. The program should accept code written in Pascal and convert it to an equival...

  •  Convert a text file to uppercase

    This C# exercise involves creating a program that reads a text file and dumps its content into another file, making a transformation in the process. The transformatio...

  •  Convert any file to uppercase

    This C# exercise involves creating a program that reads a file of any kind and dumps its content into another file, applying a transformation in the process. The tran...

  •  File inverter

    This C# exercise involves creating a program to "invert" a file. The program must take an original file and create a new one with the same name but with the ".inv" ex...

  •  File encrypter

    This C# exercise involves creating a program to encrypt a text file into another text file. The program should be able to read the content of a text file, apply an en...

  •  Count words

    This C# exercise involves creating a program to count the number of words stored in a text file. The program should read the content of a text file, process it, and c...