using System.Text; namespace ElectricLocomotive; public class LocosGenericStorage { readonly Dictionary> _electricLocoStorages; public List Keys => _electricLocoStorages.Keys.ToList(); private readonly int _pictureWidth; private readonly int _pictureHeight; private static readonly char _separatorForKeyValue = '|'; private readonly char _separatorRecords = ';'; private static readonly char _separatorForObject = ':'; public LocosGenericStorage(int pictureWidth, int pictureHeight) { _electricLocoStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } public void AddSet(string name) { _electricLocoStorages.Add(name, new LocosGenericCollection (_pictureWidth, _pictureHeight)); } public void DelSet(string name) { if (!_electricLocoStorages.ContainsKey(name)) return; _electricLocoStorages.Remove(name); } public LocosGenericCollection? this[string ind] { get { if (_electricLocoStorages.ContainsKey(ind)) return _electricLocoStorages[ind]; return null; } } public bool SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } StringBuilder data = new(); foreach (KeyValuePair> record in _electricLocoStorages) { StringBuilder records = new(); foreach (DrawingLocomotiv? elem in record.Value.GetLocos) { records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); } if (data.Length == 0) { throw new Exception("Невалиданя операция, нет данных длясохранения"); } string toWrite = $"LocoStorage{Environment.NewLine}{data}"; var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); using (StreamWriter sw = new(filename)) { foreach (var str in strs) { sw.WriteLine(str); } } return true; } public bool LoadData(string filename) { if (!File.Exists(filename)) { throw new Exception("Файл не найден"); } using (StreamReader sr = new(filename)) { string str = sr.ReadLine(); var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { throw new Exception("Нет данных для загрузки"); } if (!strs[0].StartsWith("LocoStorage")) { throw new Exception("Неверный формат данных"); } _electricLocoStorages.Clear(); do { string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 2) { str = sr.ReadLine(); continue; } LocosGenericCollection collection = new(_pictureWidth, _pictureHeight); string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { DrawingLocomotiv? monorail = elem?.CreateDrawingLoco(_separatorForObject, _pictureWidth, _pictureHeight); if (monorail != null) { if (!(collection + monorail)) { throw new Exception("Ошибка добавления в коллекцию"); } } } _electricLocoStorages.Add(record[0], collection); str = sr.ReadLine(); } while (str != null); } return true; } }