Search code examples
c#.netxmlmemory-leaksdispose

How to close a XML FileStream


I'm using this code below to read .xml file & transfer data to 4 checkboxes. But im getting the error

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

I thought it could be because the reading or writing, but closed both as you can see the code below. Any ideas?

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

Solution

  • Make user you Dispose your Disposable objects to release references/memory and also it closes the underlying stream.

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

    EDIT

    If above didn't fix the error, probably Text Changed event(data1_TextChanged) fires too often. Try this functionality on TextBox LostFocus or with a button click event.