C#中读取和更改APP.config配置文件?解决方法
C#中读取和更改APP.config配置文件?
配置文件如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connection>
<add name="ServerName" connectionString=".\sql2000" />
<add name="DataBaseName" connectionString="pubs"/>
<add name="UserID" connectionString="sa"/>
<add name="PassWord" connectionString=""/>
</connection>
</configuration>
怎样读取和更改这个配置文件?
------解决思路----------------------
获取
string ServerName= ConfigurationManager.ConnectionStrings["ServerName"].ConnectionString;//ServerName== add节点的name
其他同理
------解决思路----------------------
或者操作xml来获取和修改
------解决思路----------------------
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string conn = config.ConnectionStrings.ConnectionStrings["ServerName"].ConnectionString;
string conn = "新的值";
config.ConnectionStrings.ConnectionStrings["ServerName"].ConnectionString = conn;
config.Save();
------解决思路----------------------
通过操作xml文件实现修改配置文件中ip的值
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");//载入文件
System.Xml.XmlNode xNode;
System.Xml.XmlElement xElemip;
System.Xml.XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings");
xElemip = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='IP']");
if (xElemip != null) xElemip.SetAttribute("value","修改的值" );
else
{
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("key", "IP");
xElem2.SetAttribute("value", "写入的值");
xNode.AppendChild(xElem2);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
------解决思路----------------------
------解决思路----------------------
你要看生成后的config文件,,,
命名空间.vshost.exe.config
------解决思路----------------------
//------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 , CDPF , Ltd.
//------------------------------------------------------------
using System;
using System.Configuration;
using System.Windows.Forms;
using Utilities;
namespace DirectSeeding
{
/// <summary>
/// FrmConfig
/// 读取配置文件
///
/// 修改纪录
///
/// 2011.01.14 版本: 1.0 JiRiGaLa 完善程序的注释等、从新整理代码。
///
/// 版本:1.0
///
/// <author>
/// <name>JiRiGaLa</name>
/// <date>2011.01.14</date>
/// </author>
/// </summary>
public partial class FrmConfig : Form
{
public FrmConfig()
{
InitializeComponent();
}
/// <summary>
/// 读取配置文件
/// </summary>
private void GetConfig()
{
this.txtWriteFileName.Text = ConfigurationManager.AppSettings["WriteFileName"];
this.txtWritePath.Text = ConfigurationManager.AppSettings["WritePath"].Replace("
------解决思路----------------------
", Environment.NewLine);
this.txtPostMessageURL.Text = ConfigurationManager.AppSettings["PostMessageURL"];
this.txtLeasedLineURL.Text = ConfigurationManager.AppSettings["LeasedLineURL"];
}
private void FrmDirectSeeding_Load(object sender, EventArgs e)
{
this.GetConfig();
}
/// <summary>
/// 保存配置文件
/// </summary>
private void SaveConfig()
{
// 写入参数设置 www.wanxinyi.com
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings["WriteFileName"].Value = this.txtWriteFileName.Text;
configuration.AppSettings.Settings["WritePath"].Value = this.txtWritePath.Text.Trim().Replace(Environment.NewLine, "
------解决思路----------------------
");
configuration.AppSettings.Settings["PostMessageURL"].Value = this.txtPostMessageURL.Text;
configuration.AppSettings.Settings["LeasedLineURL"].Value = this.txtLeasedLineURL.Text;
configuration.Save();
// 重新读取参数
ConfigurationManager.RefreshSection("appSettings");
WriteFile.WriteFileName = ConfigurationManager.AppSettings["WriteFileName"];
WriteFile.WritePath = ConfigurationManager.AppSettings["WritePath"].Split('
------解决思路----------------------
');
PostMessage.PostMessageURL = ConfigurationManager.AppSettings["PostMessageURL"];
// PostMessage.LeasedLineURL = ConfigurationManager.AppSettings["LeasedLineURL"];
}
private void btnSavaConfig_Click(object sender, EventArgs e)
{
// 保存设置 www.shiapifa.com
SaveConfig();
}
}
}
------解决思路----------------------
C#修改app.config配置文件信息//更新app.config的函数
private void UpdateConfig(string Xvalue)
{
XmlDocument doc = new XmlDocument();
doc.Load(Application.ExecutablePath+".config");
XmlNode node = doc.SelectSingleNode(@"//add[@key='ServerName']");
XmlElement ele = (XmlElement)node;
ele.SetAttribute("value",Xvalue);
doc.Save(Application.ExecutablePath+".config");
}
//配置文件的源文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ServerName" value=""/>
</appSettings>
</configuration>
配置文件如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connection>
<add name="ServerName" connectionString=".\sql2000" />
<add name="DataBaseName" connectionString="pubs"/>
<add name="UserID" connectionString="sa"/>
<add name="PassWord" connectionString=""/>
</connection>
</configuration>
怎样读取和更改这个配置文件?
------解决思路----------------------
获取
string ServerName= ConfigurationManager.ConnectionStrings["ServerName"].ConnectionString;//ServerName== add节点的name
其他同理
------解决思路----------------------
或者操作xml来获取和修改
/// <summary>
/// 获取指定节点下面对应属性的值
/// </summary>
/// <param name="strFileName">文件路径</param>
/// <param name="nodeName">节点名称</param>
/// <param name="nodeDir">指定节点所在的节点目录</param>
/// <param name="attribute">节点对应的属性名称</param>
/// <returns></returns>
public static string GetNodeValue(string strFileName, string nodeName, string nodeDir, string attribute)
{
string value = null;
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(strFileName);
XmlNodeList nodeList = xmlDoc.SelectSingleNode(nodeDir).ChildNodes;//获取bookstore节点的所有子节点
foreach (XmlNode xn in nodeList) //遍历所有子节点
{
XmlElement xe = (XmlElement)xn; //将子节点类型转换为XmlElement类型
if (xe.Name == nodeName)
{
//value = xe.InnerText.Trim();
value = (xe).Attributes[attribute].Value;
break;
}
}
}
catch (Exception exp)
{
throw exp;
}
return value;
}
/// <summary>
/// 修改指定结点值
/// </summary>
/// <param name="strFileName">文件路径</param>
/// <param name="nodeName">节点名称</param>
/// <param name="value">设置后的值</param>
/// <param name="nodeDir">指定节点所在的节点目录</param>
/// <returns></returns>
public static bool UpdateNoteValue(string strFileName, string nodeName, string value, string nodeDir)
{
bool isSucceed = false;
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(strFileName);
XmlNodeList nodeList = xmlDoc.SelectSingleNode(nodeDir).ChildNodes;//获取bookstore节点的所有子节点
foreach (XmlNode xn in nodeList) //遍历所有子节点
{
XmlElement xe = (XmlElement)xn; //将子节点类型转换为XmlElement类型
if (xe.Name == nodeName)
{
xe.InnerText = value;
isSucceed = true;
break;
}
}
xmlDoc.Save(strFileName);
}
catch (Exception exp)
{
throw exp;
}
return isSucceed;
}
------解决思路----------------------
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string conn = config.ConnectionStrings.ConnectionStrings["ServerName"].ConnectionString;
string conn = "新的值";
config.ConnectionStrings.ConnectionStrings["ServerName"].ConnectionString = conn;
config.Save();
------解决思路----------------------
通过操作xml文件实现修改配置文件中ip的值
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");//载入文件
System.Xml.XmlNode xNode;
System.Xml.XmlElement xElemip;
System.Xml.XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings");
xElemip = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='IP']");
if (xElemip != null) xElemip.SetAttribute("value","修改的值" );
else
{
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("key", "IP");
xElem2.SetAttribute("value", "写入的值");
xNode.AppendChild(xElem2);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
------解决思路----------------------
public class ConfigHelper
{
/// <summary>
/// 根据键值获取配置文件
/// </summary>
/// <param name="key">键值</param>
/// <returns></returns>
public static string GetConfig(string key)
{
string val = string.Empty;
if (ConfigurationManager.AppSettings.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; }
}
}
------解决思路----------------------
你要看生成后的config文件,,,
命名空间.vshost.exe.config
------解决思路----------------------
//------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 , CDPF , Ltd.
//------------------------------------------------------------
using System;
using System.Configuration;
using System.Windows.Forms;
using Utilities;
namespace DirectSeeding
{
/// <summary>
/// FrmConfig
/// 读取配置文件
///
/// 修改纪录
///
/// 2011.01.14 版本: 1.0 JiRiGaLa 完善程序的注释等、从新整理代码。
///
/// 版本:1.0
///
/// <author>
/// <name>JiRiGaLa</name>
/// <date>2011.01.14</date>
/// </author>
/// </summary>
public partial class FrmConfig : Form
{
public FrmConfig()
{
InitializeComponent();
}
/// <summary>
/// 读取配置文件
/// </summary>
private void GetConfig()
{
this.txtWriteFileName.Text = ConfigurationManager.AppSettings["WriteFileName"];
this.txtWritePath.Text = ConfigurationManager.AppSettings["WritePath"].Replace("
------解决思路----------------------
", Environment.NewLine);
this.txtPostMessageURL.Text = ConfigurationManager.AppSettings["PostMessageURL"];
this.txtLeasedLineURL.Text = ConfigurationManager.AppSettings["LeasedLineURL"];
}
private void FrmDirectSeeding_Load(object sender, EventArgs e)
{
this.GetConfig();
}
/// <summary>
/// 保存配置文件
/// </summary>
private void SaveConfig()
{
// 写入参数设置 www.wanxinyi.com
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings["WriteFileName"].Value = this.txtWriteFileName.Text;
configuration.AppSettings.Settings["WritePath"].Value = this.txtWritePath.Text.Trim().Replace(Environment.NewLine, "
------解决思路----------------------
");
configuration.AppSettings.Settings["PostMessageURL"].Value = this.txtPostMessageURL.Text;
configuration.AppSettings.Settings["LeasedLineURL"].Value = this.txtLeasedLineURL.Text;
configuration.Save();
// 重新读取参数
ConfigurationManager.RefreshSection("appSettings");
WriteFile.WriteFileName = ConfigurationManager.AppSettings["WriteFileName"];
WriteFile.WritePath = ConfigurationManager.AppSettings["WritePath"].Split('
------解决思路----------------------
');
PostMessage.PostMessageURL = ConfigurationManager.AppSettings["PostMessageURL"];
// PostMessage.LeasedLineURL = ConfigurationManager.AppSettings["LeasedLineURL"];
}
private void btnSavaConfig_Click(object sender, EventArgs e)
{
// 保存设置 www.shiapifa.com
SaveConfig();
}
}
}
------解决思路----------------------
C#修改app.config配置文件信息//更新app.config的函数
private void UpdateConfig(string Xvalue)
{
XmlDocument doc = new XmlDocument();
doc.Load(Application.ExecutablePath+".config");
XmlNode node = doc.SelectSingleNode(@"//add[@key='ServerName']");
XmlElement ele = (XmlElement)node;
ele.SetAttribute("value",Xvalue);
doc.Save(Application.ExecutablePath+".config");
}
//配置文件的源文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ServerName" value=""/>
</appSettings>
</configuration>