我有许多运行的应用程序相互通信,但这些应用程序都没有自己的用户界面。我有一个系统控制台应用程序,它充当系统的用户界面(即所有应用程序都相互通信)。
我希望能够使用系统控制台来读取和修改每个非gui应用程序的配置。
每个应用程序都有一个使用Visual Studio设置GUI创建的app.config文件。这些设置都在应用程序范围内,这导致app.config文件看起来像这样:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="ExternalConfigReceiver.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<ExternalConfigReceiver.Properties.Settings>
<setting name="Conf1" serializeAs="String">
<value>3</value>
</setting>
<setting name="Conf2" serializeAs="String">
<value>4</value>
</setting>
</ExternalConfigReceiver.Properties.Settings>
</applicationSettings>
我尝试使用以下代码来阅读配置设置:
System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
fileMap.ExeConfigFilename = "PATH_TO_THE_FOLDER\\app.config";
System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
someVariable = config.AppSettings.Settings["Conf1"];
someVariable2 = config.AppSettings.Settings["Conf2"];
然而,仔细检查config.AppSettings对象后,我发现它不包含任何设置。
我做错了什么?我使用错误的方法来读取配置文件吗?这种方法最适合不同类型的配置文件吗?
答案 0 :(得分:4)
可以将配置文件用作XML,然后使用XPath更改值:
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);
}
}
Conf1的可能路径:
"configuration/applicationSettings/ExternalConfigReceiver.Properties.Settings/setting[name=\"Conf1\"]/value"
答案 1 :(得分:-1)
据我所知,您无法使用System.Configuration.Configuration访问其他应用程序的配置文件
它们是xml文件,您可以使用xml namspace与它们进行交互