C# app.config配置appSettings标签

C# app.config配置appSettings标签 appSettings Settings config app. app 配置 标签 C#

AppSettings标签主要用于应用程中的一些配置信息。比如上传文件的路径,需要用到的可能会根据不同环境改变的一些常量等。可以在配置文件添加可执行文件要的配置。

using System;
using System.Collections.Generic;
using System.Configuration;

class Program
{
    static void Main(string[] args)
    {
        string valstr;
        string bl;
       
        bl =ReadAppSettings("Setting1",out valstr);
        if (bl == "true")
            Console.WriteLine("Setting1值:{0}", valstr);
        else
            Console.WriteLine("错误:" + bl);
        bl = ReadAppSettings("Setting2", out valstr);
        if (bl == "true")
            Console.WriteLine("Setting2值:{0}", valstr);
        else
            Console.WriteLine("错误:" + bl);
        bl = AddUpdateAppSettings("NewSetting", "May 7, 2014");
        if (bl == "true")
            Console.WriteLine("添加标签成功。");
        else
            Console.WriteLine("错误:" + bl);
        bl = AddUpdateAppSettings("Setting1", "May 8, 2014");
        if (bl == "true")
            Console.WriteLine("修改标签成功。");
        else
            Console.WriteLine("错误:" + bl);

        List<(string, string)> list;
        bl = ReadAllAppSettings(out list);
        if (bl == "true")
            foreach (var val in list)
            {
                Console.WriteLine("键:{0}, 值:{1},", val.Item1, val.Item2);
            }
        else
            Console.WriteLine("错误:" + bl);
      
        Console.ReadKey();
    }

    /// <summary>
    /// AppSettings标签读取全部值
    /// </summary>
    /// <param name="values">返回List<(string, string)>格式数据,使用out关键字。</param>
    /// <returns>成功返回字符串“true”,失败返回原因。</returns>
    public static string ReadAllAppSettings(out List<(string, string)> values)
    {
        values = null;
        try
        {
            var appSettings = ConfigurationManager.AppSettings;
            if (appSettings.Count == 0) { return "无AppSettings标签。"; }
            values = new List<(string, string)>();
            foreach (var key in appSettings.AllKeys)
            {
                values.Add((key, appSettings[key]));
            }
            return "true";
        }
        catch (ConfigurationErrorsException err)
        {
            return err.Message;
        }
    }
    /// <summary>
    /// AppSettings标签读取指定值
    /// </summary>
    /// <param name="key">指定键</param>
    /// <param name="val">输出值,使用out关键字</param>
    /// <returns>成功返回字符串“true”,失败返回原因。</returns>
    public static string ReadAppSettings(string key, out string val)
    {
        val = null;
        try
        {
            var appSettings = ConfigurationManager.AppSettings;
            val = appSettings[key];
            if (val == null) return (key + "键值为空。");
            if (val == "") return (key + "键值为空。");
            return "true";
        }
        catch (ConfigurationErrorsException err)
        {
            return err.Message;
        }
    }
    /// <summary>
    /// AppSettings标签写入或更新配置数据
    /// </summary>
    /// <param name="key">键</param>
    /// <param name="value">值</param>
    /// <returns>成功返回字符串“true”,失败返回原因。</returns>
    public static string 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);
            return "true";
        }
        catch (ConfigurationErrorsException err)
        {
            return err.Message;
        }
    }
}

第一次程序运行结果。

Setting1值:Not Found
Setting1值:Not Found
键:NewSetting, 值:May 7, 2014,
键:Setting1, 值:May 8, 2014,

第一次程序运行后,ConsoleApp1.exe.Config数据,会创建<appSettings>标签,数据保存到标签内。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="NewSetting" value="May 7, 2014" />
        <add key="Setting1" value="May 8, 2014" />
    </appSettings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
</configuration>

第二次程序运行结果。

Setting1值:May 8, 2014
Setting1值:Not Found
键:NewSetting, 值:May 7, 2014,
键:Setting1, 值:May 8, 2014,

ConsoleApp1.exe.Config数据没有改变。

评论