Лабораторная работа №6

This commit is contained in:
victinass 2024-04-28 22:22:14 +04:00
parent 69ba7b26d6
commit ec73e88d07

View File

@ -28,6 +28,12 @@ public class StorageCollection<T>
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<string, ICollectionGenericObjects<T>>();
} }
private readonly string _collectionKey = "CollectionsStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
/// </summary> /// </summary>
@ -35,10 +41,10 @@ public class StorageCollection<T>
/// <param name="collectionType">Тип коллекции</param> /// <param name="collectionType">Тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
if (_storages.ContainsKey(name)) {
return; return;
}
// TODO Прописать логику для добавления // TODO Прописать логику для добавления
if (collectionType == CollectionType.List) if (collectionType == CollectionType.List)
{ {
@ -80,52 +86,41 @@ public class StorageCollection<T>
} }
} }
private readonly string _collectionKey = "CollectionsStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
/// <summary> /// <summary>
/// Сохранение информации по кораблям в хранилище в файл /// Сохранение информации по кораблям в хранилище в файл
/// </summary> /// </summary>
/// <param name="filname"></param> /// <param name="filname"></param>
/// <returns></returns> /// <returns></returns>
public bool SaveData(string filname) public bool SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; return false;
} }
if (File.Exists(filname)) if (File.Exists(filename))
{ {
File.Delete(filname); File.Delete(filename);
} }
if (File.Exists(filname)) using (StreamWriter writer = new StreamWriter(filename))
{ {
File.Delete(filname); writer.Write(_collectionKey);
}
StringBuilder sb = new();
sb.Append(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
sb.Append(Environment.NewLine); writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции // не сохраняем пустые коллекции
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
sb.Append(value.Key); writer.Write(value.Key);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType); writer.Write(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
sb.Append(value.Value.MaxCount); writer.Write(value.Value.MaxCount);
sb.Append(_separatorForKeyValue); writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
{ {
@ -135,14 +130,11 @@ public class StorageCollection<T>
continue; continue;
} }
sb.Append(data); writer.Write(data);
sb.Append(_separatorItems); writer.Write(_separatorItems);
}
} }
} }
using FileStream fs = new(filname, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
return true; return true;
} }
@ -158,51 +150,46 @@ public class StorageCollection<T>
return false; return false;
} }
string bufferTextFromFile = ""; using (StreamReader reader = File.OpenText(filename))
using (FileStream fs = new(filename, FileMode.Open))
{ {
byte[] b = new byte[fs.Length]; string str = reader.ReadLine();
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (str == null || str.Length == 0)
if (strs == null || strs.Length == 0)
{ {
return false; return false;
} }
if (!strs[0].Equals(_collectionKey))
if (!str.StartsWith(_collectionKey))
{ {
//если нет такой записи, то это не те файлы //если нет такой записи, то это не те данные
return false; return false;
} }
_storages.Clear(); _storages.Clear();
foreach (string data in strs) string strs = "";
while ((strs = reader.ReadLine()) != null)
{ {
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 4)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T> collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; return false;
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawingWarship() is T warship) if (elem?.CreateDrawingWarship() is T bulldozer)
{ {
if (collection.Insert(warship) == -1) if (collection.Insert(bulldozer) == -1)
{ {
return false; return false;
} }
@ -211,9 +198,16 @@ public class StorageCollection<T>
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
}
return true; return true;
} }
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType) private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{ {
return collectionType switch return collectionType switch