以编程方式向App.config添加密钥C#

时间:2015-09-18 19:43:08

标签: c# app-config

我尝试以编程方式添加并将密钥保存到App.config文件中。我的代码在下面,我已经看到了很多不同的例子,而且我的工作没有用。我试图添加一个全新的密钥,而不是修改现有密钥。这是一个控制台应用程序,我确实添加了对System.configuration的引用。

Program.cs的

using System;
using System.Linq;
using System.Text;
using System.Configuration;

namespace AddValuesToConfig
{
    class Program
    {
        static void Main(string[] args)
        {

            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config.AppSettings.Settings.Add("key1", "value");

            // Save the changes in App.config file.

            config.Save(ConfigurationSaveMode.Modified);

        }
    }
}

的App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>

    </appSettings>
</configuration>

1 个答案:

答案 0 :(得分:0)

写:

 public static bool SetAppSettings<TType>(string key, TType value)
    {
        try
        {
            if (string.IsNullOrEmpty(key))
                return false;

            Configuration appConfig = ConfigurationManager.OpenExeConfiguration(GetCurrentApplicationPath());
            AppSettingsSection appSettings = (AppSettingsSection)appConfig.GetSection("appSettings");
            if (appSettings.Settings[key] == null)
                appSettings.Settings.Add(key, value.ToString());
            else
                appSettings.Settings[key].Value = value.ToString();
            appConfig.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
            return true;
        }
        catch
        {
            return false;
        }
    }

供阅读:

public static TType GetAppSettings<TType>(string key, TType defaultValue = default(TType))
    {
        try
        {
            if (string.IsNullOrEmpty(key))
                return defaultValue;
            AppSettingsReader appSettings = new AppSettingsReader();
            return (TType)appSettings.GetValue(key, typeof(TType));
        }
        catch
        {
            return defaultValue;
        }
    }