app.config文件的读与写的问题
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
</configSections>
<dataConfiguration defaultDatabase="SMSRouter" />
<connectionStrings>
<add name="SMS" connectionString="workstation id=ACER;packet size=4096;user id=sa_smsrouter;data source=127.0.0.1;persist security info=True;initial catalog=SMS;password=sad;" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ThreadSleepTime" value="1000" />
<add key="ThreadAutoSendThreadNum" value="5" />
</appSettings>
</configuration>
想通过界面来分别修改key="ThreadSleepTime" 与key="ThreadAutoSendThreadNum" 的数值。我现在是通过读写XML方式来操作。代码如下:public static void UpdateConfig(int Number ,string Leixing) //Leixing用来区分是时间还是线程的数目
{
try
{
string m_strFullPath = "";
XmlDocument xmlDoc = new XmlDocument();
XmlNodeList nodeList;
m_strFullPath = System.Windows.Forms.Application.ExecutablePath + ".config";
xmlDoc.Load(m_strFullPath);
//文件属性的控制(读->写)
if ((File.GetAttributes(m_strFullPath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
File.SetAttributes(m_strFullPath, FileAttributes.Normal);
}
XmlNodeList nodeList = xmlDoc.SelectSingleNode(@"/configuration/appSettings").ChildNodes;
foreach (XmlNode xn in nodeList)//遍历所有子节点
{
XmlElement xe = (XmlElement)xn;
if (Leixing == "ThreadAutoSendThreadNum")
{
if (GetIndex(xe, "key", "ThreadAutoSendThreadNum") != -1)
{
string LastestValue = "value=" + Number + ";";
xe.SetAttribute("value", LastestValue);
}
}
else
{
if (GetIndex(xe, "key", "ThreadSleepTime") != -1)
{
string LastestValue = "value=" + Number + ";";
xe.SetAttribute("value", LastestValue);
}
}
}
xmlDoc.Save(m_strFullPath);
////文件属性的控制(写->读)
File.SetAttributes(m_strFullPath, FileAttributes.ReadOnly);
}
catch (Exception ex)
{
throw ex;
}
private static int GetIndex(XmlElement xe,string KeyName,string ValueName)
{
return xe.GetAttribute(KeyName).IndexOf(Name);
}
但这样写以后就把Value的值都给变了。大家有没有什么好的办法啊。求教了。