This commit is contained in:
Victoria_Isaeva 2024-05-02 11:25:51 +04:00
parent 38f2153806
commit 3cdfe42762
2 changed files with 91 additions and 76 deletions

View File

@ -21,11 +21,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count; public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } public int MaxCount { set { if (value > 0) { _maxCount = value; } } get { return Count; } }
public CollectionType GetCollectionType => CollectionType.List; public CollectionType GetCollectionType => CollectionType.List;
public int MaxCount { get; set; }
/// <summary> /// <summary>
/// Конструктор /// Конструктор

View File

@ -10,25 +10,38 @@ namespace ProjectAirBus.CollectionGenericObjects;
public class StorageCollection<T> public class StorageCollection<T>
where T : DrawningBus where T : DrawningBus
{ {/// <summary>
/// Словарь (хранилище) с коллекциями
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; /// </summary>
private Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<string> Keys => _storages.Keys.ToList();
private readonly string _collectionKey = "CollectionStorage"; /// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|"; private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItem = ";"; /// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<string, ICollectionGenericObjects<T>>();
} }
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
@ -65,114 +78,117 @@ public class StorageCollection<T>
return _storages[name]; return _storages[name];
} }
} }
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename) public bool SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; return false;
} }
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
StringBuilder sb = new();
sb.Append(_collectionKey);
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
sb.Append(Environment.NewLine); streamWriter.Write(Environment.NewLine);
if (value.Value.Count == 0)
{ if (value.Value.Count == 0)
continue; {
continue;
} }
sb.Append(value.Key); streamWriter.Write(value.Key);
sb.Append(_separatorForKeyValue); streamWriter.Write(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType); streamWriter.Write(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue); streamWriter.Write(_separatorForKeyValue);
sb.Append(value.Value.MaxCount); streamWriter.Write(value.Value.MaxCount);
sb.Append(_separatorForKeyValue); streamWriter.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
{ {
string data = item?.GetDataForSave() ?? string.Empty; string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data)) if (string.IsNullOrEmpty(data))
{ {
continue; continue;
} }
sb.Append(data);
sb.Append(_separatorItem);
streamWriter.Write(data);
streamWriter.Write(_separatorItems);
} }
} }
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding().GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
return true; return true;
} }
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// </summary>
/// <param name="filename"></param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename) public bool LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; return false;
} }
string bufferTextFromFile = ""; using (StreamReader sr = new StreamReader(filename))
using (FileStream fs = new(filename, FileMode.Open))
{ {
byte[] b = new byte[fs.Length]; string? str;
UTF8Encoding temp = new UTF8Encoding(true); str = sr.ReadLine();
while (fs.Read(b, 0, b.Length) > 0) if (str != _collectionKey.ToString())
{
bufferTextFromFile += temp.GetString(b);
}
}
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length == 0 || strs == null)
{
return false;
}
if (!strs[0].Equals(_collectionKey))
{
return false;
}
_storages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false; return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries); _storages.Clear();
foreach (string elem in set)
while ((str = sr.ReadLine()) != null)
{ {
if (elem?.CreateDrawningBus() is T bus) string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4)
{ {
if (collection.Insert(bus) == -1) continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBus() is T aircraft)
{ {
return false; if (collection.Insert(aircraft) == -1)
return false;
} }
} }
_storages.Add(record[0], collection);
} }
_storages.Add(record[0], collection);
} }
return true; return true;
} }
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType) private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{ {
return collectionType switch return collectionType switch