我的XML文件包含这样的设置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="UpdateReportService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<UpdateReportService.Properties.Settings>
<setting name="Path" serializeAs="String">
<value>C:\1</value>
</setting>
<setting name="Branch" serializeAs="String">
<value>200</value>
</setting>
<setting name="b204" serializeAs="String">
<value>192.168.1.55</value>
</setting>
<setting name="b200" serializeAs="String">
<value>192.168.0.83</value>
</setting>
<setting name="Hour" serializeAs="String">
<value>11</value>
</setting>
</UpdateReportService.Properties.Settings>
</applicationSettings>
</configuration>
我想在安装程序期间将某些值更改为用户键入的值。
我在VB上找到示例并尝试将其转换为c#:
namespace InstallConfigurator
{
[RunInstaller(true)]
public class SettingsClass : Installer
{
public override void Install(System.Collections.IDictionary stateSaver)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Context.Parameters["TARGETDIR"].ToString() + "UpdateReportService.exe");
ClientSettingsSection applicationSettingsSection = (ClientSettingsSection)config.SectionGroups["applicationSettings"].Sections["UpdateReportService.Properties.Settings"];
SettingElement Elem = applicationSettingsSection.Settings["Branch"];
applicationSettingsSection.Settings.Remove(Elem);
Elem.Value.ValueXml.InnerXml = "30000";
applicationSettingsSection.Settings.Add(Elem);
config.Save(ConfigurationSaveMode.Full);
}
}
}
但是在这个地方得到错误“由于其保护级别而无法访问”:
SettingElement Elem = applicationSettingsSection.Settings["Branch"];
那么,是否可以在c#上访问App.config中的部分并进行更改。
UPD。 2012.02.10
我用这种方式解决了问题:namespace InstallConfigurator
{
[RunInstaller(true)]
public class SettingsClass : Installer
{
public override void Install(System.Collections.IDictionary stateSaver)
{
string xml = Context.Parameters["TARGETDIR"].ToString() + "UpdateReportService.exe.config";
XmlDocument document = new XmlDocument();
document.Load(xml);
XPathNavigator navigator = document.CreateNavigator();
XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);
foreach (XPathNavigator nav in navigator.Select(@"/configuration/applicationSettings/UpdateReportService.Properties.Settings/setting[@name='Branch']/value"))
{
nav.SetValue(Context.Parameters["BRANCH"].ToString());
}
foreach (XPathNavigator nav in navigator.Select(@"/configuration/applicationSettings/UpdateReportService.Properties.Settings/setting[@name='Path']/value"))
{
nav.SetValue(Context.Parameters["PATH"].ToString());
}
document.Save(xml);
}
}
}
答案 0 :(得分:2)
在类似的项目中,我的方式略有不同:
{Branch}
”等占位符的“myapp.exe.config.default”文件。30000
”)。在我们的应用程序中运行非常流畅。