保存时C#崩溃(doc.Save(PATH);)

时间:2014-07-16 00:18:59

标签: c# xml save

此程序在调试时崩溃并突出显示" doc.Save(PATH);"在代码的最后。 我正在尝试将变量cookieScoreadditionAdditionadditionMultiplier保存到XML文件中。

我从这里获得有关它的信息" http://visualcsharptutorials.com/net-framework/writing-xml-file"

private XmlDocument doc;
string PATH = @"C:\sample.xml";
private void saveBtn_Click(object sender, EventArgs e)
{
    doc = new XmlDocument();
    if (!System.IO.File.Exists(PATH))
    {
        XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
        XmlComment comment = doc.CreateComment("This is saved game data");
        XmlElement root = doc.CreateElement("data");
        XmlElement data = doc.CreateElement("data");
        XmlAttribute addition = doc.CreateAttribute("addition");
        XmlElement additionNumber = doc.CreateElement("additionNumber");
        XmlElement multiplicationNumber = doc.CreateElement("multiplicationNumber");
        XmlElement cookieSave = doc.CreateElement("cookieSave");

        addition.Value = "addition";
        additionNumber.InnerText = additionAddition.ToString();
        multiplicationNumber.InnerText = additionMultiplier.ToString();
        cookieSave.InnerText = cookieScore.ToString();

        doc.AppendChild(declaration);
        doc.AppendChild(comment);
        doc.AppendChild(root);
        root.AppendChild(data);
        data.Attributes.Append(addition);
        data.AppendChild(cookieSave);
        data.AppendChild(additionNumber);
        data.AppendChild(multiplicationNumber);

        doc.Save(PATH);
    }
    else
    {
    }

1 个答案:

答案 0 :(得分:0)

我猜您是因为您尝试写入C驱动器的根目录而获得与访问相关的异常。请尝试写入您的桌面:

string PATH = @"C:\Users\[yourusername]\Desktop\sample.xml";

另一个选择是尝试以管理员身份运行您的EXE。如果它有效,那么你就知道这是你的问题。