“另存为…”菜单项

本文关键字:另存为 菜单项 | 更新日期: 2023-09-27 18:09:22

我正试图为"另存为…"菜单项编写代码。我的代码是这样的:

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文件以不同的名称保存在我想要的任何地方。

“另存为…”菜单项

当前代码将抛出异常,因为您的XmlDocument不包含根节点。还要记住,SaveFileDialog's Filename属性也包含扩展名。

您可以使用

创建一个没有根节点的新文件
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);
}

您新创建的XmlDocument文档实例没有任何根元素,因此XmlException

可以避免使用saveFileDialog1.FileName.ToString(),因为saveFileDialog1.FileName已经是一个字符串值。

此代码

document.Save(fileName+ ".xml");
应该

document.Save(saveFileDialog1.FileName);
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);
}