请问如何修改配置文件app.config的值
传入的参数为
modifyXml( "IntervalTime ", "60 ");
我的方法
private void modifyXml(string xmlkey, string xmlvalue)
{
Assembly ass = Assembly.GetExecutingAssembly();
string fullPath = ass.Location.Substring(0, ass.Location.LastIndexOf(@ "\ "));
fullPath = fullPath + @ "\CareHealth.vshost.exe.config ";
//MessageBox.Show(fullPath);
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(fullPath);
XmlNodeList xnlist = xmldoc.SelectSingleNode( "configuration ").ChildNodes;
foreach (XmlNode xn in xnlist)
{
XmlElement xe = (XmlElement)xn;
if (xe.InnerXml.IndexOf( " <add key=\ " " + xmlkey + "\ " ") != -1)
{
xe.SetAttribute( "value ", xmlvalue);
break;
}
}
xmldoc.Save(fullPath);
}
配置文件
<?xml version= "1.0 " encoding= "utf-8 " ?>
<configuration>
<configSections>
<sectionGroup name= "applicationSettings " type= "System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 " >
<section name= "CareHealth.Settings1 " type= "System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 " requirePermission= "false " />
</sectionGroup>
</configSections>
<appSettings>
<add key= "IntervalTime " value= "3600000 " />
</appSettings>
</configuration>
谢谢,请帮忙!
[解决办法]
App.config也是一个xml文件
按照xml文件的操作处理就行
[解决办法]
给你一段我这边已经运行过的代码:
1.读取配置文件:
private System.Xml.XmlDocument xDoc = null;
/// <summary>
/// 获取key值
/// </summary>
/// <param name= "AppKey "> key名称 </param>
/// <returns> key值 </returns>
private string GetConfigKeyValue(string AppKey)
{
string path = " ";
XmlNode xNode;
XmlElement xElem;
try
{
path = Application.StartupPath + "\\TagsValueTransForm.exe.config ";
if(xDoc == null)
{
xDoc = new System.Xml.XmlDocument();
xDoc.Load(path);
}
}
catch(Exception)
{
throw new Exception( "未发现配置文件: "+path);
}
try
{
xNode = xDoc.SelectSingleNode( "//appSettings ");
xElem = (XmlElement)xNode.SelectSingleNode( "//add[@key= ' " + AppKey + " '] ");
if ( xElem != null )
return xElem.GetAttribute( "value ");else
return " ";
}
catch(Exception ex)
{
throw ex;
}
}
2。修改配置文件:
/// <summary>
/// 修改配置文件
/// </summary>
/// <param name= "AppKey "> key名称 </param>
/// <param name= "AppValue "> key值 </param>
private void UpdateConfig(string AppKey, string AppValue)
{
string path = " ";
XmlNode xNode;
XmlElement xElem;
try
{
path = Application.StartupPath + "\\TagsValueTransForm.exe.config ";
if(xDoc == null)
{
xDoc = new System.Xml.XmlDocument();
xDoc.Load(path);
}
}
catch(Exception)
{
throw new Exception( "未发现配置文件: "+path);
}
try
{
xNode = xDoc.SelectSingleNode( "//appSettings ");
xElem = (XmlElement)xNode.SelectSingleNode( "//add[@key= ' " + AppKey + " '] ");
if ( xElem != null ) xElem.SetAttribute( "value ",AppValue);
xDoc.Save(path);
}
catch(Exception ex)
{
throw ex;
}
}