C# 使用配置文件的一些记录


C# 读写配置文件

1. 引用】中添加【System.Configuration】 2. 类文件引用

using System.Configuration;

3. 使用 1. 读取配置文件

//读取路径上的配置文件
string path=Application.StartupPath+"\\myConf.config";
Configuration conf =ConfigurationManager.OpenExeConfiguration(path);
//读取  项目名称.config
Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  1. 节点读取
//读取appSetting下面key的节点
config.AppSettings.Settings[key].Value.ToString();
  1. 设置appSetting节点下key,value
        public static bool SetConfigValue(string key, string value)
        {
            try {
                Configuration conf;
                if (conf.AppSettings.Settings[key] != null)
                conf.AppSettings.Settings[key].Value = value;
                else conf.AppSettings.Settings.Add(key, value);
                conf.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
                return true;
            } catch {
                return false;
            }
        }
  1. App.config示例
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

    <appSettings>
        <add key="name" value="config file"/>
        <add key="host" value="http://192.168.1.1"/>
    </appSettings>
</configuration>