Сериализация в C#

29.03.2015 at 14:18

public static void SerializeObjectToFile<T>(T serializingObject, string path)
{
  XmlSerializer writer = new XmlSerializer(typeof(T));
  using (StreamWriter file = new StreamWriter(path))
  {
    writer.Serialize(file, serializingObject);
  }
}
 
public static T DeserializeObjectFromFile<T>(string path)
{
  using (StreamReader file = new StreamReader(path))
  {
    XmlSerializer reader = new XmlSerializer(typeof(T));
    return (T)reader.Deserialize(file);
  }
}

private static T DeserializeObject<T>(System.IO.Stream stream)
{
    var reader = new System.Xml.Serialization.XmlSerializer(typeof(T));
    return (T)reader.Deserialize(stream);
}

private static T DeserializeObject<T>(System.IO.StreamReader streamReader)
{
    var reader = new System.Xml.Serialization.XmlSerializer(typeof(T));
    return (T)reader.Deserialize(streamReader);
}

public static T DeserializeObjectFromFile<T>(string path)
{
    if (System.IO.File.Exists(path))
    {
        using (var file = new System.IO.StreamReader(path))
        {
            return DeserializeObject<T>(file);
        }
    }
    else
        return System.Activator.CreateInstance<T>();
}

public static T DeserializeObjectFromString<T>(string s)
{
    return DeserializeObject<T>(new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(s)));
}

public static void SerializeObjectToFile<T>(object serializingObject, string path)
{
    var writer = new System.Xml.Serialization.XmlSerializer(typeof(T));
    using (var file = new System.IO.StreamWriter(path))
    {
        writer.Serialize(file, serializingObject);
    }
}


На обновления блога теперь можно подписаться Вконтакте