如何在安装程序项目中编写app.config并在程序中使用它

7
  • 我创建了一个继承安装程序(Installer)的Installhelper.cs。
  • 使用以下代码覆盖(Override) Install() 方法。(A)

将这些值插入到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 textBox 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"];

            MessageBox.Show(userName);
            MessageBox.Show(password);
            MessageBox.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>
2个回答

7
这段代码的问题在于这行代码。
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

它在安装过程中没有提供配置文件依赖的路径。所以必须将其更改为:
string path = Path.Combine(new DirectoryInfo(Context.Parameters["assemblypath"].ToString()).Parent.FullName, "[project name].exe")

    Configuration config = ConfigurationManager.OpenExeConfiguration(path);

现在它正在运行。 :)

1
谢谢。我们遇到了完全相同的问题,但是一直无法弄清为什么它无法写入文件。我所做的唯一不同之处就是从应用程序获取路径。
string path = Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(path);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接