如何关闭 XML FileStream

How to close a XML FileStream

我正在使用下面的代码读取 .xml 文件并将数据传输到 4 个复选框。但是我收到错误

"The process cannot access the file: CXXXX Because its being used by another process"

我认为这可能是因为读取或写入,但都关闭了,您可以看到下面的代码。有什么想法吗?

    private void Form1_Load(object sender, EventArgs e)
    {
        if (File.Exists("data.xml"))
        {
            XmlSerializer xs = new XmlSerializer(typeof(Information));
            FileStream read = new FileStream("data.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
            Information info = (Information)xs.Deserialize(read);

            data1.Text = info.Data1;
            data2.Text = info.Data2;
            data4.Text = info.Data3;
            data4.Text = info.Data4;

            read.Close();
        }
    }



// this class to write the data into xml file
class SaveXML
{
    public static void SaveData(object obj, string filename)
    {
        XmlSerializer sr = new XmlSerializer(obj.GetType());

        TextWriter writer = new StreamWriter(filename);
        sr.Serialize(writer, obj);
        writer.Close();        
    }
}


    // using this to update the .xml file with new data when textchanged
    private void data1_TextChanged(object sender, EventArgs e)
    {
        try
        {
            Information info = new Information();
            info.Data1 = data1.Text;
            SaveXML.SaveData(info, "data.xml");                
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

让用户释放 Disposable 对象以释放 references/memory 并关闭底层流。

 private void Form1_Load(object sender, EventArgs e)
    {
        if (File.Exists("data.xml"))
        {
            using (FileStream read = new FileStream("data.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
           {
                XmlSerializer xs = new XmlSerializer(typeof(Information))
                Information info = (Information)xs.Deserialize(read);

                 data1.Text = info.Data1;
                 data2.Text = info.Data2;
                 data4.Text = info.Data3;
                 data4.Text = info.Data4;
          }
        }
    }


class SaveXML
{
    public static void SaveData(object obj, string filename)
    {
        using(TextWriter writer = new StreamWriter(filename))
        {
            XmlSerializer sr = new XmlSerializer(obj.GetType());

            sr.Serialize(writer, obj);
        }     
    }
}

编辑

如果以上未能修复错误,可能是文本更改事件 (data1_TextChanged) 触发过于频繁。在 TextBox LostFocus 上或使用按钮单击事件尝试此功能。