【问题标题】:C# crashes on save (doc.Save(PATH);)C# 在保存时崩溃 (doc.Save(PATH);)
【发布时间】:2014-07-16 00:18:58
【问题描述】:

此程序在调试时崩溃并突出显示“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
    {
    }

【问题讨论】:

  • 发布您的堆栈跟踪,以便人们可以帮助您
  • 确切的错误信息是什么?
  • System.UnauthorizedAccessException @har07
  • @user3733200:试试我下面的建议。鉴于异常类型,我现在很肯定这就是您遇到的问题。

标签: c# xml save


【解决方案1】:

我的猜测是你得到了一个与访问相关的异常,因为你试图写入你的 C 驱动器的根目录。请尝试写入您的桌面:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    相关资源
    最近更新 更多