保存配置设置

时间:2019-08-29 07:07:40

标签: configurationmanager

我是C#新秀。我想保存配置设置以便在应用重启时重新加载,但是我在理解配置管理器的工作方式时遇到了麻烦。我在MSDN上找到了这个例子。我了解这只是在创建哈希(键,值对)。但是我不知道app.config文件在哪里(甚至怎么访问它)。有人可以通过一些示例为我提供很好的讨论吗?

使用系统;
使用System.Configuration;

命名空间ConsoleApplication1
{
    课程计划
    {
        静态void Main(string [] args)
        {
            ReadAllSettings();
            ReadSetting(“ Setting1”);
            ReadSetting(“ NotValid”);
            AddUpdateAppSettings(“ NewSetting”,“ 2014年5月7日”);
            AddUpdateAppSettings(“ Setting1”,“ 2014年5月8日”);
            ReadAllSettings();
        }

    static void ReadAllSettings()  
    {  
        try  
        {  
            var appSettings = ConfigurationManager.AppSettings;  

            if (appSettings.Count == 0)  
            {  
                Console.WriteLine("AppSettings is empty.");  
            }  
            else  
            {  
                foreach (var key in appSettings.AllKeys)  
                {  
                    Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);  
                }  
            }  
        }  
        catch (ConfigurationErrorsException)  
        {  
            Console.WriteLine("Error reading app settings");  
        }  
    }  

    static void ReadSetting(string key)  
    {  
        try  
        {  
            var appSettings = ConfigurationManager.AppSettings;  
            string result = appSettings[key] ?? "Not Found";  
            Console.WriteLine(result);  
        }  
        catch (ConfigurationErrorsException)  
        {  
            Console.WriteLine("Error reading app settings");  
        }  
    }  

    static void AddUpdateAppSettings(string key, string value)  
    {  
        try  
        {  
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
            var settings = configFile.AppSettings.Settings;  
            if (settings[key] == null)  
            {  
                settings.Add(key, value);  
            }  
            else  
            {  
                settings[key].Value = value;  
            }  
            configFile.Save(ConfigurationSaveMode.Modified);  
            ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);  
        }  
        catch (ConfigurationErrorsException)  
        {  
            Console.WriteLine("Error writing app settings");  
        }  
    }  
}  

}

0 个答案:

没有答案