.net下的配置文件分两种一种那个是应用程序配置文件,一种是web程序配置文件。C#操作配置文件时,通过ConfigurationManager来管理配置文件。
查询配置文件
利用ConfigurationManager.AppSettions根据key获取相应的value
string value=ConfigurationManager.AppSettings["test"]; //test为key值
更新、添加配置文件
public static bool SetConfig(string key, string value)
{
try
{
Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (!conf.AppSettings.Settings.AllKeys.Contains(key)) //查询配置文件中是否存在此key
{
conf.AppSettings.Settings.Add(key, value); //添加
}
else
{
conf.AppSettings.Settings[key].Value = value; //更新
conf.Save();
return true;
}
}
catch
{
return false;
}
}
总结:
对配置文件的操作还可以利用XmlDocument进行操作。下一次会总结。