static void Main(string[] args) { /*БСБО-05-19 * Копейкин Д.С. * 1. Вывести информацию в консоль о логических дисках, именах, метке тома, размере типе файловой системы. * 2. Работа с файлами ( класс File, FileInfo, FileStream и другие) * a) Создать файл * b) Записать в файл строку * c) Прочитать файл в консоль * d) Удалить файл * 3. Работа с форматом JSON * 4. Работа с форматом XML * 5. Создание zip архива, добавление туда файла, определение размера архива * */ Console.Write("Введите номер задания "); while (true) { switch (Console.ReadLine()) { case "1": #region задание 1 #region текст задания //.Вывести информацию в консоль о логических дисках, именах, метке тома, размере типе файловой системы. #endregion DriveInfo[] drives = DriveInfo.GetDrives(); foreach (DriveInfo drive in drives) { Console.WriteLine($"Название: {drive.Name}"); Console.WriteLine($"Тип: {drive.DriveType}"); if (drive.IsReady) { Console.WriteLine($"Объемдиска: {drive.TotalSize}"); Console.WriteLine($"Свободноепространство: {drive.TotalFreeSpace}"); Console.WriteLine($"Метка: {drive.VolumeLabel}"); } Console.ReadKey(); } #endregion break; case "2": #region задание 2 #region текст задания //Работа с файлами(класс File, FileInfo, FileStream и другие) // a) Создать файл // b) Записать в файл строку // c) Прочитать файл в консоль // d) Удалить файл #endregion Console.InputEncoding = Encoding.Unicode; using (var sw = new StreamWriter(@"text.txt", false, Encoding.Unicode)) //не стал создавать аудиторий и помещать туда файл, т.к. не знаю, где их стоит создавать не на своем пк, поэто файл будеи помещен "имя папки проэкта"/bin/debug/text.txt { Console.Write("Введите текст для записи в файл:"); sw.WriteLine(Console.ReadLine()); } using (var sr = new StreamReader(@"text.txt", Encoding.Unicode)) { Console.WriteLine("нажмите клавишу для считывания текста из файла"); Console.ReadKey(); while (!sr.EndOfStream) { Console.WriteLine(sr.ReadLine()); } } Console.WriteLine("Нажмите кнопку для удаления файла"); Console.ReadKey(); File.Delete(@"text.txt"); Console.WriteLine("задание завершено"); #endregion break; case "3": #region задание 3 #region текст задания //Работа с форматом JSON #endregion User user1 = new User { Name = "Bill Gates", Age = 48, Company = "Microsoft" }; //первый пользователь создан автоматически User user2 = new User(); Console.WriteLine("Введите имя второго человека"); user2.Name = Console.ReadLine(); Console.WriteLine("возраст"); user2.Age = int.Parse(Console.ReadLine()); Console.WriteLine("наименование компании"); user2.Company = Console.ReadLine(); List <User> users = new List <User> { user1, user2 }; var json = new DataContractJsonSerializer(typeof(List <User>)); using (var file = new FileStream("users.json", FileMode.Create)) //опять файл будет создан в "имя папки проэкта"/bin/debug/users.json { json.WriteObject(file, users); } using (var file = new FileStream("users.json", FileMode.OpenOrCreate)) { var newUsers = json.ReadObject(file) as List <User>; if (newUsers != null) { foreach (var user in newUsers) { { Console.WriteLine(user); } } } } Console.WriteLine("Нажмите кнопку для удаления файла"); Console.ReadKey(); File.Delete(@"users.json"); Console.WriteLine("задание завершено"); Console.ReadLine(); #endregion break; case "4": #region задание 4 #region текст задания //Работа с форматом XML #endregion User user3 = new User { Name = "Bill Gates", Age = 48, Company = "Microsoft" }; //первый пользователь создан автоматически User user4 = new User(); Console.WriteLine("Введите имя второго человека"); user4.Name = Console.ReadLine(); Console.WriteLine("возраст"); user4.Age = int.Parse(Console.ReadLine()); Console.WriteLine("наименование компании"); user4.Company = Console.ReadLine(); List <User> users2 = new List <User> { user3, user4 }; var xml = new XmlSerializer(typeof(List <User>)); using (var file = new FileStream("users.xml", FileMode.Create)) //опять файл будет создан в "имя папки проэкта"/bin/debug/users.xml { xml.Serialize(file, users2); } Console.WriteLine("для чтения файла нажмите клавишу"); Console.ReadKey(); using (var file = new FileStream("users.xml", FileMode.OpenOrCreate)) { var newUsers = xml.Deserialize(file) as List <User>; if (newUsers != null) { foreach (User user in users2) { { Console.WriteLine(user); } } } } Console.WriteLine("Нажмите кнопку, для удаления файла"); Console.ReadKey(); File.Delete(@"users.xml"); Console.WriteLine("задание завершено"); #endregion break; case "5": #region задание 5 #region текст задания //Создание zip архива, добавление туда файла, определение размера архива #endregion using (var sw = new StreamWriter(@"text2.txt", false, Encoding.Unicode)) //не стал создавать аудиторий и помещать туда файл, т.к. не знаю, где их стоит создавать не на своем пк, поэто файл будеи помещен "имя папки проэкта"/bin/debug/text.txt { sw.WriteLine("asdjdsjgnjdncvubbhxcvnbmcjbnjfdnkfmgksndkfmlsdmf"); } string sourceFile = @"text2.txt"; // исходныйфайл string compressedFile = @"text2.gz"; // сжатыйфайл using (FileStream sourceStream = new FileStream(sourceFile, FileMode.OpenOrCreate)) { using (FileStream targetStream = File.Create(compressedFile)) { using (GZipStream compressionStream = new GZipStream(targetStream, CompressionMode.Compress)) { sourceStream.CopyTo(compressionStream); Console.WriteLine("Сжатиефайла {0} завершено. Исходныйразмер: {1} сжатыйразмер: {2}.", sourceFile, sourceStream.Length.ToString(), targetStream.Length.ToString()); } } } #endregion break; default: Console.WriteLine("неверно указанно задание"); break; } } }
static void Main(string[] args) { //Из лабораторной №5 выберите класс с наследованием и / или //композицией / агрегацией для сериализации. Выполните //сериализацию / десериализацию объекта используя //a.бинарный, var stone1 = new Stone { Color = "Белый", Price = 20, Status = ProductStatus.Ready, Weight = 100 }; // создаем объект BinaryFormatter BinaryFormatter formatter = new BinaryFormatter(); // получаем поток, куда будем записывать сериализованный объект using (FileStream fs = new FileStream("Product1.dat", FileMode.OpenOrCreate)) { formatter.Serialize(fs, stone1); } // десериализация using (FileStream fs = new FileStream("Product1.dat", FileMode.OpenOrCreate)) { Stone newStone = (Stone)formatter.Deserialize(fs); Console.WriteLine($"{newStone}"); } //b.SOAP, var pStone1 = new Stone { Color = "Желтый", Price = 40, Status = ProductStatus.Ready, Weight = 40 }; SoapFormatter soapFormatter = new SoapFormatter(); using (Stream fStream = new FileStream("Product2.soap", FileMode.Create)) { soapFormatter.Serialize(fStream, pStone1); } using (FileStream fs = new FileStream("Product2.soap", FileMode.Open)) { Stone newStone2 = (Stone)soapFormatter.Deserialize(fs); Console.WriteLine($"{newStone2}"); } //c.JSON формат var ruby1 = new Stone { Color = "Red", Price = 57, Status = ProductStatus.None, Weight = 30 }; DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(Stone)); using (FileStream fs = new FileStream("Product3.json", FileMode.OpenOrCreate)) { jsonFormatter.WriteObject(fs, ruby1); } using (FileStream fs = new FileStream("Product3.json", FileMode.OpenOrCreate)) { Stone newStone3 = (Stone)jsonFormatter.ReadObject(fs); Console.WriteLine($"{newStone3}"); } //d.XML формат var diamond1 = new Stone { Color = "Прозрачный", Price = 89, Status = ProductStatus.Ready, Weight = 28 }; XmlSerializer xml = new XmlSerializer(typeof(Stone)); using (FileStream fs = new FileStream("Product4.xml", FileMode.OpenOrCreate)) { xml.Serialize(fs, diamond1); } using (FileStream fs = new FileStream("Product4.xml", FileMode.OpenOrCreate)) { Stone newStone4 = xml.Deserialize(fs) as Stone; Console.WriteLine($"{newStone4}"); } //2.Создайте коллекцию(массив) объектов и выполните //сериализацию / десериализацию. var s1 = new Stone { Color = "Розовый", Price = 57, Status = ProductStatus.None, Weight = 30 }; var s2 = new Stone { Color = "Синий", Price = 89, Status = ProductStatus.Ready, Weight = 28 }; var s3 = new Stone { Color = "Зелёный", Price = 30, Status = ProductStatus.None, Weight = 41 }; var s4 = new Stone { Color = "Чёрный", Price = 50, Status = ProductStatus.Ready, Weight = 44 }; Stone[] arr = new Stone[] { s1, s2, s3, s4 }; DataContractSerializer array = new DataContractSerializer(typeof(Stone[])); using (FileStream fs = new FileStream("array.xml", FileMode.OpenOrCreate)) { array.WriteObject(fs, arr); } using (FileStream fs = new FileStream("array.xml", FileMode.OpenOrCreate)) { Stone[] newS = (Stone[])array.ReadObject(fs); foreach (Stone s in newS) { Console.WriteLine($"{s}"); } } //3.Используя XPath напишите два селектора для вашего XML документа. XmlDocument xDoc = new XmlDocument(); xDoc.Load("array.xml"); XmlElement xRoot = xDoc.DocumentElement; XmlNodeList all = xRoot.SelectNodes("*"); //выбирает все узлы foreach (XmlNode x in all) { Console.WriteLine(x.OuterXml); //вывод всей разметки } XmlNode parts = xRoot.FirstChild; //выбирает узлы Stone Console.WriteLine(parts.FirstChild.InnerText); //вывод значения первого узла //4.Используя Linq to XML(или Linq to JSON) создайте новый xml(json) - документ и напишите несколько запросов. XDocument xdoc = new XDocument(); XElement stoneshop = new XElement("stoneshop"); //первый эл XAttribute bs_name_attr = new XAttribute("name", "theorite"); XElement bs_country_elem = new XElement("country", "Belgium"); XElement bs_auc_elem = new XElement("auction", "yes"); stoneshop.Add(bs_name_attr); //заполняем аттрибутом и элем-ми stoneshop.Add(bs_country_elem); stoneshop.Add(bs_auc_elem); XElement stoneshop2 = new XElement("stoneshop"); // второй эл XAttribute bs_name_attr2 = new XAttribute("name", "ametrine"); XElement bs_country_elem2 = new XElement("country", "Bolivia"); XElement bs_auc_elem2 = new XElement("auction", "yes"); stoneshop2.Add(bs_name_attr2); //заполняем аттрибутом и элем-ми stoneshop2.Add(bs_country_elem2); stoneshop2.Add(bs_auc_elem2); XElement root = new XElement("root"); //корневой элемент root.Add(stoneshop); root.Add(stoneshop2); xdoc.Add(root); xdoc.Save("linq.xml"); //сохраняем в файл Console.WriteLine("Где найти Аметрин?"); //1-й запрос var items = xdoc.Element("root").Elements("stoneshop") .Where(p => p.Attribute("name").Value == "ametrine") .Select(p => p); foreach (var item in items) { Console.WriteLine(item.Element("country").Value); } Console.WriteLine("Какие камни представлены на аукционе?");//2-й запрос var coun = xdoc.Element("root").Elements("stoneshop") .Where(p => p.Element("auction").Value == "yes") .Select(p => p); foreach (var c in coun) { Console.WriteLine(c.Attribute("name").Value); } }
static void Main(string[] args) { Collection <Box> boxes = null; DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Collection <Box>)); try { using (FileStream fs = new FileStream(@"../../../ConsoleApp65/bin/Debug/boxes.json", FileMode.Open)) { boxes = (Collection <Box>)(ser.ReadObject(fs)); } } catch (ArgumentException e) { Console.WriteLine(e.Message); } catch (IOException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } foreach (Box box in boxes) { Console.WriteLine(box); } var first = from box in boxes where (box.GetLongestSideSize() > 3) orderby box.GetLongestSideSize() descending select box; Console.WriteLine("First linq"); foreach (var box in first) { Console.WriteLine(box); } Console.WriteLine("Second linq"); var second = from box in boxes group box by box.Weight; foreach (var key in second) { Console.WriteLine(key.Key); foreach (var val in key) { Console.WriteLine($"\t\t\t{val}"); } } var third = from box in boxes where (box.Weight == boxes.Max(x => x.Weight)) select box; Console.WriteLine("Third linq"); foreach (var th in third) { Console.WriteLine(th); } Console.WriteLine(third.LongCount()); }