Сохранение и запись через StreamWriter и StreamReader

This commit is contained in:
Павел Ладягин 2024-04-17 17:05:21 +04:00
parent e9e19bd2cd
commit 15565fd27b

View File

@ -1,4 +1,5 @@
using System.Text;
using System.IO;
using System.Text;
using ProjectAirplaneWithRadar.Drawnings;
namespace ProjectAirplaneWithRadar.CollectionGenericObjects
@ -105,22 +106,23 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
if(File.Exists(filename))
File.Delete(filename);
StringBuilder sb = new();
sb.Append(_collectionKey);
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter sw = new StreamWriter(fs);
sw.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
sb.Append(Environment.NewLine);
sw.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);
sw.Write(value.Key);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.GetCollectionType);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.MaxCount);
sw.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
@ -130,14 +132,10 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
sw.Write(data);
sw.Write(_separatorItems);
}
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
return true;
}
@ -153,32 +151,25 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
return false;
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
using StreamReader sr = new StreamReader(fs);
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!strs[0].Equals(_collectionKey))
if (!str.Equals(_collectionKey))
{
return false;
}
_storages.Clear();
foreach (string data in strs)
while (!sr.EndOfStream)
{
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
@ -202,10 +193,9 @@ namespace ProjectAirplaneWithRadar.CollectionGenericObjects
return false;
}
}
_storages.Add(record[0], collection);
}
}
return true;
}