[英]How to close a XML FileStream
I'm using this code below to read .xml file & transfer data to 4 checkboxes. 我在下面使用此代码读取.xml文件并将数据传输到4个复选框。 But im getting the error 但是我收到错误
"The process cannot access the file: CXXXX Because its being used by another process" “该进程无法访问文件:CXXXX,因为它正在被另一个进程使用”
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);
}
}
Make user you Dispose your Disposable objects to release references/memory and also it closes the underlying stream. 使用户成为您的Disposable对象,以释放引用/内存,并关闭基础流。
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. 如果上述方法不能解决错误,则可能是Text Changed事件(data1_TextChanged)触发得太多了。 Try this functionality on TextBox LostFocus or with a button click event. 在TextBox LostFocus上或通过按钮单击事件尝试此功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.