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 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 int MaxCount { get; set; }
/// <summary>
/// Конструктор

View File

@ -10,25 +10,38 @@ namespace ProjectAirBus.CollectionGenericObjects;
public class StorageCollection<T>
where T : DrawningBus
{
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
{/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
private Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
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 _separatorItem = ";";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
}
public void AddCollection(string name, CollectionType collectionType)
{
@ -65,114 +78,117 @@ public class StorageCollection<T>
return _storages[name];
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(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)
{
sb.Append(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
streamWriter.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.GetCollectionType);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItem);
{
continue;
}
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;
}
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// </summary>
/// <param name="filename"></param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
using (StreamReader sr = new StreamReader(filename))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b, 0, b.Length) > 0)
{
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)
{
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItem, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
_storages.Clear();
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;
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch