如何在安装应用程序后更改app.config的内容

时间:2013-06-17 11:37:48

标签: c# configuration install app-config

我正在研究WPF应用程序,很快就要为安装做好准备,但是有一个功能允许用户更改app.config文件,我不知道如何从代码隐藏中做到这一点应用程序。我也不知道在安装应用程序后这将如何工作。

简单地说:我有一个窗口,允许用户在另一个应用程序的web.config中输入要搜索的文本。所以在我的app.config中我有不同的搜索,我希望在安装用户能够(在窗口的textoxes中输入值后)在应用程序的app.config中输入新值。

有人可以告诉我这是否可能并最终如何实现这一目标?

2 个答案:

答案 0 :(得分:2)

我在申请中的表现如何。我有app.config如下

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="StoreConnectionString"
          connectionString="Data Source=.\;MultipleActiveResultSets=True;Initial Catalog=Store;Integrated Security=False;"
          providerName="System.Data.SqlClient" />
    </connectionStrings>

    <appSettings>
        <add key="ExportPath" value="D:\" />
        <add key="CompanyName" value="My Company" />
        <add key="mail" value="email@mail.com" />
        <add key="phone" value="+992918254040" />
        <add key="ExpDate" value="Pink" />
        <add key="Print" value="No" />
        <add key="EnforcePassw" value="Yes"/>
    </appSettings>
</configuration>

所以我可以从我的应用程序更改和保存应用程序设置,这是代码

private void btnSave(object sender, RoutedEventArgs e)
        {
            //returns path of folder where your application is
            string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            //combines path of folder and file
            string configFile = System.IO.Path.Combine(appPath, "MyApp.exe.config");
            //Defines the configuration file mapping for an .exe application
            ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
            configFileMap.ExeConfigFilename = configFile;
            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

            config.AppSettings.Settings["ExportPath"].Value = txtExport.Text;
            config.AppSettings.Settings["CompanyName"].Value = txtComapny.Text;
            config.AppSettings.Settings["mail"].Value = txtEmail.Text;
            config.AppSettings.Settings["phone"].Value = txtPhone.Text;
            config.AppSettings.Settings["Print"].Value = print;
            config.AppSettings.Settings["EnforcePassw"].Value = password;
            config.AppSettings.Settings["ExpDate"].Value = color;
            config.Save(); 

        }

希望它会对你有所帮助!

如果要添加新字符串,请使用此代码;

        config.AppSettings.Settings.Add("Key", "Value");

答案 1 :(得分:0)

相关问题