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
C# Exercise Example
// 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.");
}
}
}
}