public static void UpdateAppSettings() {
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Add an entry to appSettings.
int appStgCnt = ConfigurationManager.AppSettings.Count;
string newKey = "NewKey" + appStgCnt.ToString(); string newValue = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString(); config.AppSettings.Settings.Add(newKey, newValue); // Save the configuration file.
config.Save(ConfigurationSaveMode.Modified); // Force a reload of the changed section.
ConfigurationManager.RefreshSection("appSettings"); }上面的只是保存到/debug/appname.exe.config 程序关闭后,这个文件就没有了
我想保存到app.config 文件里面.
有办法吗?
所以你可以重新定义一个xml来放这些信息,或者放到db中。
要不直接config.SaveAs(path);
public static void UpdateAppSettings(string key,string keyValue)//编辑参数
{
XmlDocument xmlDoc=new XmlDocument();
string configPath="appname.exe.config";
xmlDoc.Load(configPath);
XmlNode xmlNode=xmlDoc.SelectSingleNode("configuration/appSettings/add[@key='"+key+"']");
xmlNode.Attributes["value"].InnerText=keyValue;
xmlDoc.Save(configPath);
}
你可以这样保存。
string keyName = "Time";
string valueName = "Value";XmlDocument doc = new XmlDocument();
if (File.Exists(xmlFile))
{
doc.Load(xmlFile);
}XmlNode nTime = doc.SelectSingleNode(keyName);
if (nTime == null)
{
nTime = doc.CreateElement(keyName);
doc.AppendChild(nTime);
}XmlAttribute aTime = nTime.Attributes[valueName];
if (aTime == null)
{
aTime = doc.CreateAttribute(valueName);
nTime.Attributes.Append(aTime);
}DateTime now = DateTime.Now;
aTime.InnerText = string.Format("{0} {1}", now.ToLongDateString(), now.ToLongTimeString());doc.Save(xmlFile);