本文介绍了C#中的序列化/反序列化问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的小项目中实现了序列化.它工作正常,但是反序列化无效.有人可以给我发一些基本的文章吗?

我已通过以下方式实现SERIALIZATION:

I have implemented Serialization in my small project. It works fine but deserialization does not work. Can any one send me some basic article about it?

I have implemented SERIALIZATION in the following way:

// SERIALIZATION
output = new FileStream( "AppManager.am", FileMode.OpenOrCreate, FileAccess.Write );
for (int i = 0; i < m_Appointments.Count; i++)
    formatter.Serialize(output, m_Appointments[i]);
output.Close();



我知道要写入的对象数量,但是在进行反序列化的情况下,如何知道呢?



I know the number of objects to be written but in case of DESERIALIZATION, how to know it?

推荐答案



/// <summary>
/// Serializes an object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializableObject"></param>
/// <param name="fileName"></param>
public void SerializeObject<T>(T serializableObject, string fileName)
{
    if (serializableObject == null) { return; }
    try
    {
        XmlDocument xmlDocument = new XmlDocument();
        XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
        using (MemoryStream stream = new MemoryStream())
        {
            serializer.Serialize(stream, serializableObject);
            stream.Position = 0;
            xmlDocument.Load(stream);
            xmlDocument.Save(fileName);
            stream.Close();
        }
    }
    catch (Exception ex)
    {
        //Log exception here
    }
}


/// <summary>
/// Deserializes an xml file into an object list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public T DeSerializeObject<T>(string fileName)
{
    if (string.IsNullOrEmpty(fileName)) { return default(T); }
    T objectOut = default(T);
    try
    {
        string attributeXml = string.Empty;
        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.Load(fileName);
        string xmlString = xmlDocument.OuterXml;

        using (StringReader read = new StringReader(xmlString))
        {
            Type outType = typeof(T);
            XmlSerializer serializer = new XmlSerializer(outType);
            using (XmlReader reader = new XmlTextReader(read))
            {
                objectOut = (T)serializer.Deserialize(reader);
                reader.Close();
            }
            read.Close();
        }
    }
    catch (Exception ex)
    {
        //Log exception here
    }
    return objectOut;
}


这篇关于C#中的序列化/反序列化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 00:50
查看更多