安装期间更改App.config
我有这样的设置的XML文件
C:1 200 192.168.1.55 192.168.0.83 11
我想在安装程序期间将某些值更改为用户键入的值。
我在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); } } }
在类似的项目中,我的方式略有不同:
- 没有 “myapp.exe.config”文件发送您的设置。
- 而是,发送包含“
{Branch}
”等占位符的“myapp.exe.config.default”文件。 - 在安装过程中,将“myapp.exe.config.default”作为字符串加载到内存中。
- 用实际值替换占位符(例如“
30000
”)。 - 将替换的字符串写为实际文件“myapp.exe.config”。
- 奖励:在编写配置之前,检查是否存在任何现有配置文件,并将其复制为备份以保留以前的版本。
这在我们的应用程序中非常流畅。
上述就是C#学习教程:安装期间更改App.config分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/988114.html