通过频繁序列化使用Xml序列化的正确方法

时间:2010-01-09 06:45:43

标签: c# .net serialization file-io xml-serialization

我有一个列表框,当选择或取消选择某个项目时,我想将更改保存到xml文件中(因此它始终是文件的最新版本,用户不需要“保存”按钮)。

在测试时我偶尔会遇到这个IOException:

该进程无法访问文件“C:\ MyPath \ MyFile.xml”,因为它正由另一个进程使用。

这是我的XML序列化代码:

// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
    TextWriter textWriter = new StreamWriter(filename);

    xmlSerializer.Serialize(textWriter, toSerialize);
}

// Load an object from the disk
private static T DeserialzeObject<T>(String filename) where T : class
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

    try
    {
        TextReader textReader = new StreamReader(filename);
        return (T)xmlSerializer.Deserialize(textReader);
    }
    catch (FileNotFoundException)
    { }

    return null;
}

以下是它的名称:

// Save off the list because the visibility has changed
public void WorkItemColumnTypeOnVisibleChanged(int fieldID, Visibility visibility)
{
    ColumnFields.SerializeObject(ColumnFields.GetSerializeFilename());
}

反序列化是给出错误的那个:

WorkItemColumnTypes savedVersion = DeserialzeObject<WorkItemColumnTypes>(result.GetSerializeFilename());

有没有办法优化我与文件的连接,这样我才不会绊倒自己?

1 个答案:

答案 0 :(得分:5)

也许您需要在序列化和反序列化方法中的Close对象上调用TextWriter?或者使用using构造强制在块的末尾进行处理。

示例:

// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
    using(TextWriter textWriter = new StreamWriter(filename))
    {

        xmlSerializer.Serialize(textWriter, toSerialize);
    }
}

// Load an object from the disk
private static T DeserialzeObject<T>(String filename) where T : class
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

    try
    {
        using(TextReader textReader = new StreamReader(filename))
        {
            return (T)xmlSerializer.Deserialize(textReader);
        }
    }
    catch (FileNotFoundException)
    { }

    return null;
}