с# Serialization to file or string / с# Сериализация в файл или в строку + Десериализация

static void SerializeToFile(object o)
{
  XmlSerializer serializer = new XmlSerializer(o.GetType());
  using (Stream writer = new FileStream("output.xml", FileMode.Create))
  {
    serializer.Serialize(writer, o);
  }
}

public static string SerializeToString(object obj)
        {
            XmlSerializer serializer = new XmlSerializer(obj.GetType());

            using (StringWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, obj);

                return writer.ToString();
            }
        }
public static object DeserializeFromFile(object obj,string path)
{
  XmlSerializer serializer = new XmlSerializer(obj.GetType());
 
  using (XmlReader reader = XmlReader.Create(path))
  {
    object o = serializer.Deserialize(reader);
  }
}

//From string

var serializer = new XmlSerializer(typeof(Car));
using (var reader = new StringReader(xml))
{
    var car = (Car)serializer.Deserialize(reader);
}

No comments:

Post a Comment