C#: Read and modify settings in another application's app.config file

断了今生、忘了曾经 提交于 2019-12-06 11:53:12

Its possible to use the config file as XML and then use XPath to change values:

using (TransactionScope transactionScope = new TransactionScope())
{
    XmlDocument configFile = new XmlDocument();

    configFile.Load("PathToConfigFile");

    XPathNavigator fileNavigator = configFile.CreateNavigator();

    // User recursive function to get to the correct node and set the value
    WriteValueToConfigFile(fileNavigator, pathToValue, newValue);

    configFile.Save("PathToConfigFile");

    // Commit transaction
    transactionScope.Complete();
}

private void WriteValueToConfigFile(XPathNavigator fileNavigator, string remainingPath, string newValue)
{
    string[] splittedXPath = remainingPath.Split(new[] { '/' }, 2);
    if (splittedXPath.Length == 0 || String.IsNullOrEmpty(remainingPath))
    {
        throw new Exception("Path incorrect.");
    }

    string xPathPart = splittedXPath[0];
    XPathNavigator nodeNavigator = fileNavigator.SelectSingleNode(xPathPart);

    if (splittedXPath.Length > 1)
    {
        // Recursion
        WriteValueToConfigFile(nodeNavigator, splittedXPath[1], newValue);
    }
    else
    {
        nodeNavigator.SetValue(newValue ?? String.Empty);
    }
}

Possible path to Conf1:

"configuration/applicationSettings/ExternalConfigReceiver.Properties.Settings/setting[name=\"Conf1\"]/value"

as far as i know you cant use the System.Configuration.Configuration to access config files of other applications

they are xml files and you can use the xml namspace to interact with them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!