C# · 12月 22, 2021

c#-4.0 – 如何在安装项目中写入app.config并在程序中使用它

>我创建了一个Installhelper.cs,它是从安装程序中获取的.
>使用这段代码(A)覆盖Install()方法.

插入到app.config的这些值在安装后创建的[projectName] .exe.config文件中不可用.
我已经手动在app.config中添加了如下所示的部分(B)

数据传递给安装程序类,但数据不会写入app.config字段.它们在安装期间在创建的配置文件中保持相同.

任何帮助是极大的赞赏.我花了将近一天的时间.

代码A:

[RunInstaller(true)]public partial class Installation : System.Configuration.Install.Installer{ public Installation() { InitializeComponent(); } public override void Install(IDictionary stateSaver) { //base.Install(stateSaver); try { // In order to get the value from the text@R_257_2419@ named ‘EDITA1’ I needed to add the line: // ‘/PathValue = [EDITA1]’ to the CustomActionData property of the CustomAction We added. string userName = Context.Parameters[“userName”]; string password = Context.Parameters[“password”]; string folderPath = Context.Parameters[“path”]; Message@R_257_2419@.Show(userName); Message@R_257_2419@.Show(password); Message@R_257_2419@.Show(folderPath); Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //config.AppSettings.Settings.Add(“userName”,userName); //config.AppSettings.Settings.Add(“password”,password); //config.AppSettings.Settings.Add(“foderPath”,folderPath); config.AppSettings.Settings[“userName”].Value = userName; config.AppSettings.Settings[“password”].Value = password; config.AppSettings.Settings[“foderPath”].Value = folderPath; config.Save(ConfigurationSaveMode.Full); ConfigurationManager.RefreshSection(“appSettings”); } catch (FormatException e) { string s = e.Message; throw e; } }}

应用配置中添加的部分是
代码B:

<appSettings><add key=”userName” value=”” /><add key=”password” value=”” /><add key=”foderPath” value=”” /></appSettings>解决方法 谢谢.我们有这个确切的问题,无法弄清楚为什么它不会写入文件.
我做的唯一不同的事情是从应用程序获取路径. string path = Application.ExecutablePath;Configuration config = ConfigurationManager.OpenExeConfiguration(path);