Thursday, 27 February 2014

De-Serialize Object from file

public static DatabaseColumns Load(string sScopesFilePath)
{
    // Console.WriteLine(System.IO.Path.GetFullPath(sScopesFilePath));

    DatabaseColumns AllColumns = null;
    try
    {
        using (XmlReader reader = XmlReader.Create(sScopesFilePath))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(DatabaseColumns));
            AllColumns = serializer.Deserialize(reader) as DatabaseColumns;
        }
    }
    catch (Exception ex)
    {
        throw new ConfigurationErrorsException("Invalid DatabaseColumns.xml file supplied. See inner exception for details.", ex);
    }

    return AllColumns;

  }



Or

public static object Deserialize(string xml, Type toType)
{
    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
        System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
        return xSerializer.Deserialize(str);
    }

}



Or

// You must apply a DataContractAttribute or SerializableAttribute 
// to a class to have it serialized by the DataContractSerializer.
[DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
class Person : IExtensibleDataObject
{
        [DataMember()]
        public string FirstName;
        [DataMember]
        public string LastName;
        [DataMember()]
        public int ID;

etc

}

public static object Deserialize(string xml, Type toType)
{
    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
        DataContractSerializer serializer = new DataContractSerializer(toType);
        return serializer.ReadObject(reader);
    }

}





No comments:

Post a Comment