保存XML文件时出现UnauthorizedAccessException

时间:2014-12-12 17:27:54

标签: c# xml exception

我正在开发一个使用WebService连接到数据库的C#Windows窗体应用程序。 在保存XML配置文件时,它会抛出UnauthorizedAccessException。 这是负责创建XML文件的函数(它位于名为MyXmlHandler的类中):

public void CreateConfigXML(string path)
    {
        XmlDocument doc = new XmlDocument();
        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);

        XmlElement root = doc.CreateElement("configuration");
        doc.AppendChild(root);

        XmlElement epubfolder = doc.CreateElement("epubfolder");
        epubfolder.InnerText = @"C:\";
        XmlElement webservicelink = doc.CreateElement("webservicelink");
        webservicelink.InnerText = "http://localhost:20707/Service1.svc";

        root.AppendChild(epubfolder);
        root.AppendChild(webservicelink);

        doc.Save(path);
    }

这就是我使用该功能的地方:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        ...

        string xmlPath = Application.StartupPath + @"\Config\Config.xml";
        string xsdPath = Application.StartupPath + @"\Config\Config.xsd";
        MyXmlHandler xmlHandler = new MyXmlHandler(xmlPath, xsdPath);

        if (Directory.Exists(Application.StartupPath + @"\Config") && File.Exists(xmlPath) && File.Exists(xmlPath) && xmlHandler.ValidateXml())
        {
            Application.Run(form);
        }
        else
        {
            if (!Directory.Exists(Application.StartupPath + @"\Config"))
            {
                Directory.CreateDirectory(Application.StartupPath + @"\Config");
            }

            xmlHandler.CreateConfigXML(Application.StartupPath + @"\Config");
            MessageBox.Show(xmlHandler.ValidateMessage);
        }

    }
}

它在doc.Save(路径)

中抛出异常

提前致谢

1 个答案:

答案 0 :(得分:1)

您正在将目录路径传递给CreateConfigXML函数。试试这个:Application.StartupPath + @"\Config\config.xml"

修改:或者更确切地说CreateConfigXML(xmlPath)

相关问题