leila.net
leila.net

Reputation: 81

How to serialize and deserialize data in/from XML File using c#?

I'm using winforms and c# to save data in xml file. I successfully insert my data into the xml file and display it in my winform but the problem is when i close and open again the form to save again another data the system display this message:

"The process can't access to the file "xmlfile path" because it's being in use by another process"

I´m using the code below:

class information.cs:

     private string id_x;
           private string id_y;
           private string fname_x;
private string fname_y;
     public string ID_X
           {  
                  get { return id_x; }
                  set { id_x = value; }
           }

           public string ID_Y
           {
               get { return id_y; }
               set { id_y = value; }
           }

           public string Fname_X
           {
               get { return fname_x; }

               set { fname_x = value; }
           }  

  public string Fname_Y
           {
               get { return fname_y; }

               set { fname_y = value; }
           }  

Class saveXML.cs:

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

in the load form:

     if (File.Exists("Patient_Data.xml"))
                {

                    XmlSerializer xs = new XmlSerializer(typeof(Information));
                    FileStream read = new FileStream("Patient_Data.xml", FileMode.Open, FileAccess.Read);
                    Information info = (Information)xs.Deserialize(read);


                    int x1 = Int32.Parse(info.ID_X);
                    int y1 = Int32.Parse(info.ID_Y);
                    int x2 = Int32.Parse(info.Fname_X);
   int y2 = Int32.Parse(info.Fname_Y);
                this.tlp_id.Location = new Point(x1, y1);
                this.tlp_fname.Location = new Point(x2, y2);

Upvotes: 1

Views: 736

Answers (1)

Jehof
Jehof

Reputation: 35544

Your are not closing the FileStream after you have read all information from it.

FileStream read = new FileStream("Patient_Data.xml", FileMode.Open, FileAccess.Read);
Information info = (Information)xs.Deserialize(read);
read.Close();

A better way to ensure that also in case of an exception the FileStream is closed, is to use a using-statement.

using(FileStream read = new FileStream("Patient_Data.xml", FileMode.Open, FileAccess.Read)) {
  Information info = (Information)xs.Deserialize(read);
}

Upvotes: 3

Related Questions