using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Windows.Forms;
using System.Diagnostics;
namespace Config
{
/// <summary>
/// 写入【Config.ConfigAppSettings.SetValue("字段", "内容")】
/// 读取【Config.ConfigAppSettings.GetValue("字段名称")】
/// </summary>
public class ConfigAppSettings
{
public static string configfile = System.IO.Directory.GetCurrentDirectory() + "/自定义名称.config";
public static System.Configuration.Configuration config;
public static Configuration ConfigAppSettingsto(string filename)
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = filename;
config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
return config;
}
/// <summary>
/// 写入值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public static void SetValue(string key, string value)
{
config = ConfigAppSettingsto(ConfigAppSettings.configfile);
if (config.AppSettings.Settings[key] == null)
{
config.AppSettings.Settings.Add(key, value);
}
else
{
config.AppSettings.Settings[key].Value = value;
}
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
}
/// <summary>
/// 读取指定key的值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetValue(string key)
{
try
{
config = ConfigAppSettingsto(ConfigAppSettings.configfile);
if (config.AppSettings.Settings[key] == null)
{
return null;
}
else
{
return config.AppSettings.Settings[key].Value;
}
}
catch
{
return null;
}
}
}
}
Config.cs 类下载: