Exercise
Insects + persistence
Objetive
Create a new version of the "insects" exercise, which should persist the data using some form of storage such as a database or file system.
Example Code
// Importing necessary namespaces for file I/O operations and general functionality
using System; // To use general .NET functionalities
using System.Collections.Generic; // To use List for storing insect objects
using System.IO; // To perform file I/O operations
// Define a class to represent an Insect
class Insect
{
public string Name { get; set; } // Name of the insect
public string Color { get; set; } // Color of the insect
public double WingSpan { get; set; } // Wing span of the insect (in centimeters)
// Constructor to initialize the insect's properties
public Insect(string name, string color, double wingSpan)
{
Name = name; // Assign name to the insect
Color = color; // Assign color to the insect
WingSpan = wingSpan; // Assign wing span to the insect
}
// Method to represent the insect as a string (for easy display and storage)
public override string ToString()
{
return $"{Name},{Color},{WingSpan}"; // Return insect data as a comma-separated string
}
}
// Define a class to handle the persistence (save/load) of Insect data to/from a file
class InsectDataPersistence
{
private const string FilePath = "insects_data.txt"; // File path for storing insect data
// Method to save a list of insects to a file
public void SaveInsectsToFile(List insects)
{
try
{
// Open the file for writing (it will overwrite any existing data)
using (StreamWriter writer = new StreamWriter(FilePath, false))
{
// Write each insect's data as a new line in the file
foreach (var insect in insects)
{
writer.WriteLine(insect.ToString()); // Save the insect as a string
}
}
// Notify that the data has been saved successfully
Console.WriteLine("Insect data has been saved to the file.");
}
catch (Exception ex)
{
// Display an error message if something goes wrong
Console.WriteLine($"Error saving insect data to file: {ex.Message}");
}
}
// Method to load a list of insects from a file
public List LoadInsectsFromFile()
{
List insects = new List(); // List to store the loaded insects
try
{
// Open the file for reading
using (StreamReader reader = new StreamReader(FilePath))
{
string line;
// Read each line of the file
while ((line = reader.ReadLine()) != null)
{
// Split the line into parts (name, color, wing span)
var parts = line.Split(',');
// Create a new Insect object and add it to the list
insects.Add(new Insect(parts[0], parts[1], double.Parse(parts[2])));
}
}
// Notify that the data has been loaded successfully
Console.WriteLine("Insect data has been loaded from the file.");
}
catch (Exception ex)
{
// Display an error message if something goes wrong
Console.WriteLine($"Error loading insect data from file: {ex.Message}");
}
return insects; // Return the list of loaded insects
}
}
// Main class to demonstrate the insect data persistence functionality
class Program
{
static void Main(string[] args)
{
// Create a list of insects with sample data
List insects = new List
{
new Insect("Dragonfly", "Green", 15.5),
new Insect("Butterfly", "Yellow", 10.2),
new Insect("Bee", "Black and Yellow", 3.1)
};
// Create an instance of InsectDataPersistence to handle file operations
InsectDataPersistence persistence = new InsectDataPersistence();
// Save the insect data to the file
persistence.SaveInsectsToFile(insects);
// Load the insect data from the file
List loadedInsects = persistence.LoadInsectsFromFile();
// Display the loaded insects' data
Console.WriteLine("\nLoaded Insects:");
foreach (var insect in loadedInsects)
{
Console.WriteLine($"Name: {insect.Name}, Color: {insect.Color}, Wing Span: {insect.WingSpan} cm");
}
}
}