如何关闭XML文件流

本文关键字:文件 XML 何关闭 | 更新日期: 2023-09-27 18:04:56

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

"进程不能访问文件:CXXXX,因为它正在被另一个进程使用"

我认为这可能是因为读取或写入,但关闭两者,你可以看到下面的代码。什么好主意吗?

    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);
        }
    }

如何关闭XML文件流

让用户释放你的Disposable对象来释放引用/内存,同时关闭底层流。

 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或按钮单击事件上尝试此功能。