我正在尝试为“另存为...”菜单项编写代码。我的代码如下所示:
private void menuItem9_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = ".XML file (*.xml)|*.xml";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.ShowDialog();
XmlDocument document = new XmlDocument();
string fileName = saveFileDialog1.FileName.ToString();
document.Save(fileName+ ".xml");
if (!File.Exists(fileName))
{
File.Create(fileName);
}
}
基本上我想要做的就是使用“另存为”选项。点击它之后,我希望能够在我想要的任何地方保存带有不同名称的.xml文件。
答案 0 :(得分:1)
由于XmlDocument
不包含根节点,因此您的当前代码将引发异常。另请注意,SaveFileDialog's
Filename
属性还包含扩展名。
您可以使用
创建没有Root节点的新文件SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = ".XML file (*.xml)|*.xml";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.Create(saveFileDialog1.FileName);
}
或者在保存之前确保您的XmlDocument具有根节点:
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = ".XML file (*.xml)|*.xml";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
XmlDocument document = new XmlDocument();
document.AppendChild(document.CreateElement("Root"));
document.Save(saveFileDialog1.FileName);
}
答案 1 :(得分:0)
您新创建的XmlDocument
文档实例没有任何根元素,因此XmlException
您可以避免使用saveFileDialog1.FileName.ToString()
,因为saveFileDialog1.FileName
已经是字符串值。
此代码
document.Save(fileName+ ".xml");
应该是
document.Save(saveFileDialog1.FileName);
答案 2 :(得分:0)
private void menuItem9_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = ".XML file (*.xml)|*.xml";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.ShowDialog();
XmlDocument document = new XmlDocument();
//Add this line of code
document.LoadXml("<root></root>");
string fileName = saveFileDialog1.FileName.ToString();
// Save the document to a file
XmlTextWriter writer = new XmlTextWriter(fileName,null);
document.Save(writer);
}