chnage FileStream to StreamWriter and StreamReader

This commit is contained in:
MaxKarme 2022-11-16 09:28:14 +03:00
parent 1436165717
commit d2423b1bd3

View File

@ -44,61 +44,44 @@ namespace AirFighter
_mapStorages.Remove(name); _mapStorages.Remove(name);
} }
private static void WriteToFile(string text, FileStream stream)
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
public bool SaveData(string filename) public bool SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
File.Delete(filename); File.Delete(filename);
} }
using (FileStream fs = new(filename, FileMode.Create)) using (StreamWriter fs = new(filename))
{ {
WriteToFile($"MapsCollection{Environment.NewLine}", fs); fs.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages) foreach (var storage in _mapStorages)
{ {
WriteToFile($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", fs); fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
} }
} }
return true; return true;
} }
/// <summary>
/// Загрузка нформации по автомобилям на парковках из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></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 fs = new(filename))
using (FileStream fs = new(filename, FileMode.Open))
{ {
byte[] b = new byte[fs.Length]; string current = fs.ReadLine();
UTF8Encoding temp = new(true); if (!current.Contains("MapsCollection"))
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (!strs[0].Contains("MapsCollection"))
{ {
//если нет такой записи, то это не те данные //если нет такой записи, то это не те данные
return false; return false;
} }
//очищаем записи
_mapStorages.Clear(); _mapStorages.Clear();
for (int i = 1; i < strs.Length; ++i)
while ((current = fs.ReadLine()) != null)
{ {
var elem = strs[i].Split(separatorDict); var elem = current.Split(separatorDict);
AbstractMap map = null; AbstractMap map = null;
switch (elem[1]) switch (elem[1])
{ {
@ -112,6 +95,8 @@ namespace AirFighter
_mapStorages.Add(elem[0], new MapWithSetCarsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map)); _mapStorages.Add(elem[0], new MapWithSetCarsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
} }
}
return true; return true;
} }