繁体   English   中英

如何使用c#在XML文件中序列化和反序列化数据?

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

我正在使用winforms和c#将数据保存在xml文件中。 我成功地将我的数据插入到xml文件中并在我的winform中显示它,但问题是当我关闭并再次打开表单以再次保存另一个数据时系统显示此消息:

“该进程无法访问文件”xmlfile path“,因为它正被另一个进程使用”

我使用下面的代码:

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

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

在加载形式:

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

在您从中读取所有信息后,您没有关闭FileStream。

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

确保在FileStream关闭的情况下也使用using语句的更好方法。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM