From dd9105c2e4dec44fd9b71fb993e2a60513c13ddd Mon Sep 17 00:00:00 2001 From: Pavel_Sorokin Date: Mon, 7 Nov 2022 20:33:06 +0400 Subject: [PATCH] StreamWriter and StreamReader. --- Liner/Liner/MapsCollection.cs | 76 +++++++++++++++++++---------------- 1 file changed, 42 insertions(+), 34 deletions(-) diff --git a/Liner/Liner/MapsCollection.cs b/Liner/Liner/MapsCollection.cs index 09d4a38..2eed3e7 100644 --- a/Liner/Liner/MapsCollection.cs +++ b/Liner/Liner/MapsCollection.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; +using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; @@ -53,12 +55,12 @@ namespace Liner { File.Delete(filename); } - using (FileStream fs = new(filename, FileMode.Create)) + using (StreamWriter sw = new(filename)) { - WriteToFile($"MapsCollection{Environment.NewLine}", fs); + sw.Write($"MapsCollection{Environment.NewLine}"); foreach (var storage in _mapStorages) { - WriteToFile($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", fs); + sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); } } return true; @@ -70,39 +72,45 @@ namespace Liner return false; } string bufferTextFromFile = ""; - using (FileStream fs = new(filename, FileMode.Open)) + using (StreamReader sr = new(filename)) { - byte[] b = new byte[fs.Length]; - UTF8Encoding temp = new(true); - while (fs.Read(b, 0, b.Length) > 0) + bool isFirst = true; + string str; + while ((str = sr.ReadLine()) != null) { - bufferTextFromFile += temp.GetString(b); - } - } - var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - if (!strs[0].Contains("MapsCollection")) - { - return false; - } - _mapStorages.Clear(); - for (int i = 1; i < strs.Length; ++i) - { - var elem = strs[i].Split(separatorDict); - AbstractMap map = null; - switch (elem[1]) - { - case "SimpleMap": - map = new SimpleMap(); - break; - case "SeaMap": - map=new SeaMap(); - break; - case "SwampMap": - map = new SwampMap(); - break; - } - _mapStorages.Add(elem[0], new MapWithSetShipsGeneric(_pictureWidth, _pictureHeight, map)); - _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + if (isFirst) + { + if (!str.Contains("MapsCollection")) + { + return false; + } + else + { + _mapStorages.Clear(); + } + isFirst = false; + } + else + { + var tempElem = str.Split(separatorDict); + AbstractMap map = null; + switch (tempElem[1]) + { + case "SimpleMap": + map = new SimpleMap(); + break; + case "SeaMap": + map = new SeaMap(); + break; + case "SwampMap": + map = new SwampMap(); + break; + + } + _mapStorages.Add(tempElem[0], new MapWithSetShipsGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[tempElem[0]].LoadData(tempElem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + } + } } return true; }