From 44c56936ff5247c1a9b84b9f0f0260a3c8bbb9cb Mon Sep 17 00:00:00 2001 From: zum Date: Sun, 7 Apr 2024 00:10:10 +0400 Subject: [PATCH 1/4] lab6 --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 14 +- .../ListGenericObjects.cs | 23 ++- .../MassiveGenericObjects.cs | 17 +- .../StorageCollection.cs | 153 +++++++++++++++++- .../Drawnings/DrawningStormTrooper.cs | 12 +- .../Drawnings/DrawningWarPlane.cs | 12 ++ .../Drawnings/ExtentionDrawningWarPlane.cs | 54 +++++++ .../Entities/EntityStormTrooper.cs | 25 +++ .../Entities/EntityWarPlane.cs | 25 +++ .../FormWarPlaneCollection.Designer.cs | 71 +++++++- .../FormWarPlaneCollection.cs | 30 ++++ .../FormWarPlaneCollection.resx | 9 ++ 13 files changed, 434 insertions(+), 13 deletions(-) create mode 100644 ProjectStormTrooper/ProjectStormTrooper/Drawnings/ExtentionDrawningWarPlane.cs diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/AbstractCompany.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/AbstractCompany.cs index de400f8..3642e0f 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/AbstractCompany.cs @@ -49,7 +49,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ICollectionGenericObjects.cs index ecaa9c1..48a71a3 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -15,7 +15,8 @@ public interface ICollectionGenericObjects /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } + /// /// Добавление объекта в коллекцию @@ -45,4 +46,15 @@ public interface ICollectionGenericObjects /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); } \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ListGenericObjects.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ListGenericObjects.cs index e3cd42e..dda0195 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/ListGenericObjects.cs @@ -17,9 +17,20 @@ public class ListGenericObjects : ICollectionGenericObjects /// private int _maxCount; - public int Count => _collection.Count; + public int MaxCount + { + get => _maxCount; + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + public CollectionType GetCollectionType => CollectionType.List; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int Count => _collection.Count; /// /// Конструктор @@ -67,4 +78,12 @@ public class ListGenericObjects : ICollectionGenericObjects _collection.RemoveAt(position); return temp; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/MassiveGenericObjects.cs index e957d1b..4d41847 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@  + namespace ProjectStormTrooper.CollectionGenericObjects; /// @@ -15,8 +16,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -33,6 +38,8 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } + public CollectionType GetCollectionType => CollectionType.Massive; + /// /// Конструктор /// @@ -101,4 +108,12 @@ public class MassiveGenericObjects : ICollectionGenericObjects return temp; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs index df720d0..991be36 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs @@ -1,11 +1,13 @@ using ProjectStormTrooper.CollectionGenericObjects; +using ProjectStormTrooper.Drawnings; +using System.Text; /// /// Класс-хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawningWarPlane { /// /// Словарь (хранилище) с коллекциями @@ -16,6 +18,21 @@ public class StorageCollection /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор @@ -71,4 +88,138 @@ public class StorageCollection return _storages[name]; } } + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (_storages.Count == 0) + { + return false; + } + + if (File.Exists(filename)) + { + File.Delete(filename); + } + + StringBuilder sb = new(); + + sb.Append(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + sb.Append(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); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + + sb.Append(data); + sb.Append(_separatorItems); + } + } + + using FileStream fs = new(filename, FileMode.Create); + using StreamWriter streamWriter = new StreamWriter(fs); + string info = sb.ToString(); + for (int i = 0; i < info.Length; i++) + { + streamWriter.Write(info[i]); + } + + return true; + } + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + string bufferTextFromFile = ""; + using (FileStream fs = new(filename, FileMode.Open)) + { + using StreamReader streamReader = new StreamReader(fs); + string firstString = streamReader.ReadLine(); + if (!firstString.Equals(_collectionKey)) + { + //если нет такой записи, то это не те данные + return false; + } + _storages.Clear(); + while (!streamReader.EndOfStream) + { + string[] record = streamReader.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + if(record.Length != 4) + { + continue; + } + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) + { + return false; + } + + collection.MaxCount = Convert.ToInt32(record[2]); + + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawningWarPlane() is T warPlane) + { + if (!collection.Insert(warPlane)) + { + return false; + } + } + } + + _storages.Add(record[0], collection); + } + } + + + + return true; + } + + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } } \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/Drawnings/DrawningStormTrooper.cs b/ProjectStormTrooper/ProjectStormTrooper/Drawnings/DrawningStormTrooper.cs index f6b6e43..d3112c7 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/Drawnings/DrawningStormTrooper.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/Drawnings/DrawningStormTrooper.cs @@ -26,8 +26,18 @@ public class DrawningStormTrooper : DrawningWarPlane { EntityWarPlane = new EntityStormTrooper(speed, weight, bodyColor, colorOfHead, additionalColor, bombs, rockets); - } + /// + /// Конструктор принимающий объект Entity + /// + public DrawningStormTrooper(EntityWarPlane? entityWarPlane) + { + if (entityWarPlane != null) + { + EntityWarPlane = entityWarPlane; + } + } + /// /// Прорисовка объекта diff --git a/ProjectStormTrooper/ProjectStormTrooper/Drawnings/DrawningWarPlane.cs b/ProjectStormTrooper/ProjectStormTrooper/Drawnings/DrawningWarPlane.cs index 31fa1ec..44a50a0 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/Drawnings/DrawningWarPlane.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/Drawnings/DrawningWarPlane.cs @@ -75,6 +75,18 @@ namespace ProjectStormTrooper.Drawnings { EntityWarPlane = new EntityWarPlane(speed, weight, bodyColor, colorOfHead); } + + /// + /// Конструктор принимающий объект Entity + /// + public DrawningWarPlane(EntityWarPlane? entityWarPlane) + { + if(entityWarPlane != null) + { + EntityWarPlane = entityWarPlane; + } + } + /// /// Установка границ поля /// diff --git a/ProjectStormTrooper/ProjectStormTrooper/Drawnings/ExtentionDrawningWarPlane.cs b/ProjectStormTrooper/ProjectStormTrooper/Drawnings/ExtentionDrawningWarPlane.cs new file mode 100644 index 0000000..25f36b5 --- /dev/null +++ b/ProjectStormTrooper/ProjectStormTrooper/Drawnings/ExtentionDrawningWarPlane.cs @@ -0,0 +1,54 @@ +using ProjectStormTrooper.Entities; + +namespace ProjectStormTrooper.Drawnings; + +/// +/// Расширение для класса EntityWarPlane +/// +public static class ExtentionDrawningWarPlane +{ + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningWarPlane? CreateDrawningWarPlane(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityWarPlane? warPlane = EntityStormTrooper.CreateEntityStormTrooper(strs); + if (warPlane != null) + { + return new DrawningStormTrooper(warPlane); + } + + warPlane = EntityWarPlane.CreateEntityCar(strs); + if (warPlane != null) + { + return new DrawningWarPlane(warPlane); + } + + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningWarPlane drawningCar) + { + string[]? array = drawningCar?.EntityWarPlane?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + } + + return string.Join(_separatorForObject, array); + } +} \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/Entities/EntityStormTrooper.cs b/ProjectStormTrooper/ProjectStormTrooper/Entities/EntityStormTrooper.cs index aceed26..5afced5 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/Entities/EntityStormTrooper.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/Entities/EntityStormTrooper.cs @@ -44,4 +44,29 @@ public class EntityStormTrooper : EntityWarPlane Rockets = rockets; } + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityStormTrooper), Speed.ToString(), Weight.ToString(), BodyColor.Name, + ColorOfHead.Name, AdditionalColor.Name,Bombs.ToString(), Rockets.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityStormTrooper? CreateEntityStormTrooper(string[] strs) + { + if (strs.Length != 8 || strs[0] != nameof(EntityStormTrooper)) + { + return null; + } + + return new EntityStormTrooper(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), + Color.FromName(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7])); + } } \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/Entities/EntityWarPlane.cs b/ProjectStormTrooper/ProjectStormTrooper/Entities/EntityWarPlane.cs index e964843..163eaf4 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/Entities/EntityWarPlane.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/Entities/EntityWarPlane.cs @@ -43,6 +43,31 @@ namespace ProjectStormTrooper.Entities ColorOfHead = colorOfHead; } + //TODO Прописать метод + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityWarPlane), Speed.ToString(), Weight.ToString(), BodyColor.Name, ColorOfHead.Name}; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityWarPlane? CreateEntityCar(string[] strs) + { + if (strs.Length != 5 || strs[0] != nameof(EntityWarPlane)) + { + return null; + } + + return new EntityWarPlane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4])); + } } } diff --git a/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.Designer.cs b/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.Designer.cs index 0ad4f0d..3900342 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.Designer.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.Designer.cs @@ -46,10 +46,17 @@ buttonAddWarPlane = new Button(); comboBoxSelectorCompany = new ComboBox(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + SaveToolStripMenuItem = new ToolStripMenuItem(); + LoadToolStripMenuItem = new ToolStripMenuItem(); + openFileDialog = new OpenFileDialog(); + saveFileDialog = new SaveFileDialog(); groupBox1.SuspendLayout(); panelStorage.SuspendLayout(); panelCompanyTools.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBox1 @@ -59,9 +66,9 @@ groupBox1.Controls.Add(panelCompanyTools); groupBox1.Controls.Add(comboBoxSelectorCompany); groupBox1.Dock = DockStyle.Right; - groupBox1.Location = new Point(616, 0); + groupBox1.Location = new Point(616, 28); groupBox1.Name = "groupBox1"; - groupBox1.Size = new Size(197, 754); + groupBox1.Size = new Size(197, 782); groupBox1.TabIndex = 0; groupBox1.TabStop = false; groupBox1.Text = "Инструменты"; @@ -167,7 +174,7 @@ panelCompanyTools.Controls.Add(buttonAddWarPlane); panelCompanyTools.Dock = DockStyle.Bottom; panelCompanyTools.Enabled = false; - panelCompanyTools.Location = new Point(3, 493); + panelCompanyTools.Location = new Point(3, 521); panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Size = new Size(191, 258); panelCompanyTools.TabIndex = 7; @@ -234,19 +241,62 @@ // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 28); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(616, 754); + pictureBox.Size = new Size(616, 782); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(813, 28); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(59, 24); + файлToolStripMenuItem.Text = "Файл"; + // + // SaveToolStripMenuItem + // + SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + SaveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + SaveToolStripMenuItem.Size = new Size(227, 26); + SaveToolStripMenuItem.Text = "Сохранение"; + SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // LoadToolStripMenuItem + // + LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; + LoadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + LoadToolStripMenuItem.Size = new Size(227, 26); + LoadToolStripMenuItem.Text = "Загрузка"; + LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // // FormWarPlaneCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(813, 754); + ClientSize = new Size(813, 810); Controls.Add(pictureBox); Controls.Add(groupBox1); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormWarPlaneCollection"; Text = "Коллекция военных самолетов"; groupBox1.ResumeLayout(false); @@ -255,7 +305,10 @@ panelCompanyTools.ResumeLayout(false); panelCompanyTools.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -278,5 +331,11 @@ private Button buttonCollectionDel; private ListBox listBoxCollection; private Button buttonCollectionAdd; + private MenuStrip menuStrip; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem SaveToolStripMenuItem; + private ToolStripMenuItem LoadToolStripMenuItem; + private OpenFileDialog openFileDialog; + private SaveFileDialog saveFileDialog; } } \ No newline at end of file diff --git a/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.cs b/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.cs index 25ef63a..cd2a3aa 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.cs @@ -247,5 +247,35 @@ namespace ProjectStormTrooper RerfreshListBoxItems(); } + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.SaveData(saveFileDialog.FileName)) + { + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void LoadToolStripMenuItem_Click(object sender, EventArgs e) + { + if(openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog.FileName)) + { + MessageBox.Show("Загрузка прошла успешно", "Реузльтат", MessageBoxButtons.OK, MessageBoxIcon.Information); + RerfreshListBoxItems(); + } + else + { + MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } } diff --git a/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.resx b/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.resx index af32865..b7ad5cc 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.resx +++ b/ProjectStormTrooper/ProjectStormTrooper/FormWarPlaneCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 145, 17 + + + 315, 17 + \ No newline at end of file -- 2.25.1 From 55c68c2d70a25218fe7e6bb427853bb9d53784ff Mon Sep 17 00:00:00 2001 From: zum Date: Sat, 13 Apr 2024 17:35:43 +0400 Subject: [PATCH 2/4] lab6 --- .../CollectionGenericObjects/StorageCollection.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs index 991be36..2b8d442 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs @@ -160,21 +160,25 @@ public class StorageCollection return false; } - string bufferTextFromFile = ""; using (FileStream fs = new(filename, FileMode.Open)) { using StreamReader streamReader = new StreamReader(fs); string firstString = streamReader.ReadLine(); + if(firstString == null || firstString.Length == 0) + { + return false; + } if (!firstString.Equals(_collectionKey)) { //если нет такой записи, то это не те данные return false; } + _storages.Clear(); while (!streamReader.EndOfStream) { string[] record = streamReader.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); if(record.Length != 4) { continue; @@ -204,7 +208,6 @@ public class StorageCollection } - return true; } -- 2.25.1 From 34bc9b98b9bbcafbf4543439eefde21911c5270e Mon Sep 17 00:00:00 2001 From: zum Date: Mon, 15 Apr 2024 12:38:53 +0400 Subject: [PATCH 3/4] some fix --- .../CollectionGenericObjects/StorageCollection.cs | 6 +----- .../Drawnings/ExtentionDrawningWarPlane.cs | 4 ++-- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs index 2b8d442..c17bf44 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs @@ -139,11 +139,7 @@ public class StorageCollection using FileStream fs = new(filename, FileMode.Create); using StreamWriter streamWriter = new StreamWriter(fs); - string info = sb.ToString(); - for (int i = 0; i < info.Length; i++) - { - streamWriter.Write(info[i]); - } + streamWriter.Write(sb.ToString()); return true; } diff --git a/ProjectStormTrooper/ProjectStormTrooper/Drawnings/ExtentionDrawningWarPlane.cs b/ProjectStormTrooper/ProjectStormTrooper/Drawnings/ExtentionDrawningWarPlane.cs index 25f36b5..784a887 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/Drawnings/ExtentionDrawningWarPlane.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/Drawnings/ExtentionDrawningWarPlane.cs @@ -40,9 +40,9 @@ public static class ExtentionDrawningWarPlane /// /// Сохраняемый объект /// Строка с данными по объекту - public static string GetDataForSave(this DrawningWarPlane drawningCar) + public static string GetDataForSave(this DrawningWarPlane drawningWarPlane) { - string[]? array = drawningCar?.EntityWarPlane?.GetStringRepresentation(); + string[]? array = drawningWarPlane?.EntityWarPlane?.GetStringRepresentation(); if (array == null) { -- 2.25.1 From 1c65dd299d19bc1e0808c13a1c451656c62e2571 Mon Sep 17 00:00:00 2001 From: zum Date: Mon, 15 Apr 2024 13:51:34 +0400 Subject: [PATCH 4/4] lab6 Succes --- .../StorageCollection.cs | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs index c17bf44..69f9051 100644 --- a/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectStormTrooper/ProjectStormTrooper/CollectionGenericObjects/StorageCollection.cs @@ -105,24 +105,25 @@ public class StorageCollection File.Delete(filename); } - StringBuilder sb = new(); - sb.Append(_collectionKey); + using FileStream fs = new(filename, FileMode.Create); + using StreamWriter streamWriter = new StreamWriter(fs); + streamWriter.Write(_collectionKey); foreach (KeyValuePair> value in _storages) { - sb.Append(Environment.NewLine); + streamWriter.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); + streamWriter.Write(value.Key); + streamWriter.Write(_separatorForKeyValue); + streamWriter.Write(value.Value.GetCollectionType); + streamWriter.Write(_separatorForKeyValue); + streamWriter.Write(value.Value.MaxCount); + streamWriter.Write(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) { @@ -132,15 +133,10 @@ public class StorageCollection continue; } - sb.Append(data); - sb.Append(_separatorItems); + streamWriter.Write(data); + streamWriter.Write(_separatorItems); } } - - using FileStream fs = new(filename, FileMode.Create); - using StreamWriter streamWriter = new StreamWriter(fs); - streamWriter.Write(sb.ToString()); - return true; } -- 2.25.1