我的代码在使用 XmlWriter 时崩溃,说它被另一个进程使用。
private void generateXml(Control receivedControl)
{
foreach (Control subCtrl in receivedControl.Controls)
{
using (XmlWriter writer = XmlWriter.Create("C:\\ui.xml"))
{
writer.WriteStartElement(subCtrl.Name);
generateXml(subCtrl);
writer.WriteEndElement();
}
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
{
generateXml(c);
}
}
这是我调试的错误:
附加信息:该进程无法访问文件“C:\ui.xml”,因为它正被另一个进程使用。
编辑:多亏了你,我设法让递归工作,但它只写了 xml 文件中的最后一个对象,有人知道为什么吗?这是更新的代码:
private void generateXml(XmlWriter receivedWriter, Control receivedControl)
{
receivedWriter.WriteStartElement(receivedControl.Name);
foreach (Control subCtrl in receivedControl.Controls)
{
generateXml(receivedWriter, subCtrl);
}
receivedWriter.WriteEndElement();
}
private void button2_Click(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using(XmlWriter writer = XmlWriter.Create("c:\\ui.xml", settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("Form");
generateXml(writer, c);
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
}