Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Xml.Serialization;
- namespace ConsoleApp1
- {
- class Program
- {
- static void Main(string[] args)
- {
- //string directory = Path.Combine(
- // Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ProgramName");
- string directory = Path.Combine("D:\", "ProgramName");
- string file = Path.Combine(directory, "data.xml");
- Data data = new Data
- {
- Amount = 150m
- };
- Display(data, "Исходный вариант");
- try
- {
- if (!Directory.Exists(directory))
- {
- Directory.CreateDirectory(directory);
- }
- Serializer.SaveToXml(file, data);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex);
- }
- // Как будто читаем где-то в другом месте программы и не сразу же после записи
- // -----------------------------
- try
- {
- Data fromFile = null;
- if (File.Exists(file))
- {
- fromFile = Serializer.LoadXml<Data>(file);
- }
- else
- {
- fromFile = new Data();
- }
- Display(fromFile, "Прочитанный из файла");
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex);
- }
- Console.ReadKey();
- }
- private static void Display(Data data, string message)
- {
- Console.WriteLine(message + ". Amount: {0}", data.Amount);
- }
- }
- public class Data
- {
- public decimal Amount { get; set; }
- }
- public static class Serializer
- {
- public static void SaveToXml<T>(String fileName, T serializableObject)
- {
- XmlSerializer serializer = new XmlSerializer(typeof(T));
- using (TextWriter textWriter = new StreamWriter(fileName))
- {
- serializer.Serialize(textWriter, serializableObject);
- }
- }
- public static T LoadXml<T>(String fileName)
- {
- XmlSerializer serializer = new XmlSerializer(typeof(T));
- using (TextReader textReader = new StreamReader(fileName))
- {
- return (T)serializer.Deserialize(textReader);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement