FileStream заменён на StreamReader и StreamWriter

This commit is contained in:
tyxz0 2024-05-11 09:14:27 +04:00
parent a57a758f1f
commit 0b7ebcdcc0

View File

@ -4,6 +4,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace DoubleDeckerBus.CollectionGenericObjects; namespace DoubleDeckerBus.CollectionGenericObjects;
@ -90,13 +91,17 @@ public class StorageCollection<T>
File.Delete(filename); File.Delete(filename);
} }
StringBuilder sb = new(); using StreamWriter sw = new(filename);
{
sw.WriteLine(_collectionKey);
sb.Append(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
sb.Append(Environment.NewLine); StringBuilder sb = new();
// не сохраняем пустые коллекции
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
@ -118,11 +123,11 @@ public class StorageCollection<T>
sb.Append(data); sb.Append(data);
sb.Append(_separatorItems); sb.Append(_separatorItems);
} }
sw.WriteLine(sb.ToString());
}
} }
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
return true; return true;
} }
@ -134,36 +139,21 @@ public class StorageCollection<T>
return false; return false;
} }
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open)) using (StreamReader sr = new(filename))
{ {
byte[] b = new byte[fs.Length]; string? bufferLine = sr.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 (bufferLine != _collectionKey)
if (strs == null || strs.Length == 0)
{ {
return false; return false;
} }
if (!strs[0].Equals(_collectionKey))
{
//если нет такой записи, то это не те данные
return false;
}
_storages.Clear(); _storages.Clear();
foreach (string data in strs) while ((bufferLine = sr.ReadLine()) != null)
{ {
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = bufferLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 4)
{ {
@ -197,6 +187,8 @@ public class StorageCollection<T>
return true; return true;
} }
}
/// <summary> /// <summary>
/// Создание коллекции по типу /// Создание коллекции по типу
/// </summary> /// </summary>