c# 操作配置文件app.config
在c#出现以前,应用程序通常都是采用ini或xml作为配置文件,但c#出现后,大部分程序员还是选择用可操作性强的.config应用程序配置文件的。所以,为了操作方便,通常需要写一个通用类。网上有很多这样的通用类,但我觉得我写的这个通用辅助类对于我来说很方便,看各人喜好喽。
using system;
using system.collections.generic;
using system.text;
using system.configuration;
namespace schwann.commlibrary
{
public class confighelper
{
/// <summary>
/// 根据键值获取配置文件
/// </summary>
/// <param name="key">键值</param>
/// <returns></returns>
public static string getconfig(string key)
{
string val = string.empty;
if (configurationmanager.apps教程ettings.allkeys.contains(key))
val = configurationmanager.appsettings[key];
return val;
}
/// <summary>
/// 获取所有配置文件
/// </summary>
/// <returns></returns>
public static dictionary<string, string> getconfig()
{
dictionary<string, string> dict = new dictionary<string, string>();
foreach (string key in configurationmanager.appsettings.allkeys)
dict.add(key, configurationmanager.appsettings[key]);
return dict;
}
/// <summary>
/// 根据键值获取配置文件
/// </summary>
/// <param name="key">键值</param>
/// <param name="defaultvalue">默认值</param>
/// <returns></returns>
public static string getconfig(string key, string defaultvalue)
{
string val = defaultvalue;
if (configurationmanager.appsettings.allkeys.contains(key))
val = configurationmanager.appsettings[key];
if (val == null)
val = defaultvalue;
return val;
}
/// <summary>
/// 写配置文件,如果节点不存在则自动创建
/// </summary>
/// <param name="key">键值</param>
/// <param name="value">值</param>
/// <returns></returns>
public static bool setconfig(string key, string value)
{
try
{
configuration conf = configurationmanager.openexeconfiguration(configurationuserlevel.none);
if (!conf.appsettings.settings.allkeys.contains(key))
conf.appsettings.settings.add(key, value);
else
conf.appsettings.settings[key].value = value;
conf.save();
return true;
}
catch { return false; }
}
/// <summary>
/// 写配置文件(用键值创建),如果节点不存在则自动创建
/// </summary>
/// <param name="dict">键值集合</param>
/// <returns></returns>
public static bool setconfig(dictionary<string, string> dict)
{
try
{
if (dict == null || dict.count == 0)
return false;
configuration conf = configurationmanager.openexeconfiguration(configurationuserlevel.none);
foreach (string key in dict.keys)
{
if (!conf.appsettings.settings.allkeys.contains(key))
conf.appsettings.settings.add(key, dict[key]);
else
conf.appsettings.settings[key].value = dict[key];
}
conf.save();
return true;
}
catch { return false; }
}
}
}
|