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

标签 c# .net xml winforms

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

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

我使用下面的代码:

类信息.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);
}

关于c# - 如何使用 C# 序列化和反序列化 XML 文件中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30347148/

相关文章:

c# - 用另一台电脑调用一台电脑(Dial up Modem)

.net - 如何查询联结表

c# - BufferBlock 和 TPL 数据流行为

xml - 如何在 Scala 类中漂亮地表示 XML 实体?

c# - 无法解析 XmlDictionaryWriter?

c# - 强制 BindingSource 更新数据/模型

c# - 如何在 Form1 上制作一个标签,从 form2 说 "Hello"?

xml - 在 Freemarker 中使用 NetSuite 日期

c# - 调用 REST 的最简单方法

c# - TreeViews 上的附加属性