gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:36:46 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com