using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CarManagerV3 { /// /// Handles safe reading and writing of car data to files. /// internal class SafeManager { /// /// The path of the txt file that contains recently opened file paths. /// private static readonly string recentPathsFile = "recent_paths.txt"; /// /// Initializes a file at a specified path if it does not already exist. /// /// The path. public static void InitializeFile(string path) { if (!File.Exists(@path)) { using (StreamWriter writer = new StreamWriter(@path)) { // Create the file, empty writer.WriteLine(); } } } /// /// Reads cars from a specified file path. /// /// The path. /// /// A containing the cars read from the file. /// public static List ReadCars(string path) { List cars = new List(); using (StreamReader reader = new StreamReader(@path)) { string line; while ((line = reader.ReadLine()) != null) { // Process the line if (line == "") continue; cars.Add(Car.FromCsvString(line)); } } return cars; } /// /// Saves the cars to a specified file path. /// /// The path. /// A containing all cars to save. public static void SaveCars(string path, List cars) { using (StreamWriter writer = new StreamWriter(@path)) { foreach (Car car in cars) { writer.WriteLine(car.ToCsvString()); } } } /// /// Adds a file path to the recent paths list. /// If a path is already in the list, it is moved to the top. /// Otherwise, it is added to the top. /// Keeps only the 5 most recent paths. /// /// The path. public static void AddRecentPath(string path) { List paths = new List(); if (File.Exists(recentPathsFile)) { using (StreamReader reader = new StreamReader(recentPathsFile)) { string line; while ((line = reader.ReadLine()) != null) { paths.Add(line); } } } paths.Remove(path); paths.Insert(0, path); if (paths.Count > 5) { paths = paths.Take(5).ToList(); } using (StreamWriter writer = new StreamWriter(recentPathsFile)) { foreach (string p in paths) { writer.WriteLine(p); } } } /// /// Gets the recently opened file paths. /// /// /// A containing the recent file paths. /// public static List GetRecentPaths() { List paths = new List(); if (File.Exists(recentPathsFile)) { using (StreamReader reader = new StreamReader(recentPathsFile)) { string line; while ((line = reader.ReadLine()) != null) { paths.Add(line); } } } return paths; } } }