APP.Config:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
namespace WindowsFormsApplication1
{
/// <summary>
/// C#中动态读写App.config配置文件
/// </summary>
public class AppConfig
{
public AppConfig()
{
///
/// TODO: 在此处添加构造函数逻辑
///
}
/// <summary>
/// 写操作
/// </summary>
/// <param name="strExecutablePath"></param>
/// <param name="AppKey"></param>
/// <param name="AppValue"></param>
public static void ConfigSetValue(string strExecutablePath, string AppKey, string AppValue)
{
XmlDocument xDoc = new XmlDocument();
//获取可执行文件的路径和名称
xDoc.Load(strExecutablePath);
XmlNode xNode;
XmlElement xElem1;
XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings");
// xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
else
{
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("key", AppKey);
xElem2.SetAttribute("value", AppValue);
xNode.AppendChild(xElem2);
}
xDoc.Save(strExecutablePath);
}
/// <summary>
/// 读操作
/// </summary>
/// <param name="strExecutablePath"></param>
/// <param name="appKey"></param>
/// <returns></returns>
public static string ConfigGetValue(string strExecutablePath, string appKey)
{
XmlDocument xDoc = new XmlDocument();
try
{
xDoc.Load(strExecutablePath);
XmlNode xNode;
XmlElement xElem;
xNode = xDoc.SelectSingleNode("//appSettings");
xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
if (xElem != null)
return xElem.GetAttribute("value");
else
return "";
}
catch (Exception)
{
return "";
}
}
}
}调用方法:
System.IO.FileInfo FileInfo = new System.IO.FileInfo(Application.StartupPath + @"\WindowsFormsApplication1.exe.config");
if (!FileInfo.Exists) //不存在web.config文件
{
label5.Text="没有找到文统配置文件!";
}
AppConfig.ConfigSetValue(FileInfo.FullName, "server", ServerName);
AppConfig.ConfigSetValue(FileInfo.FullName, "database", DbName);
AppConfig.ConfigSetValue(FileInfo.FullName, "uid", UserName);
AppConfig.ConfigSetValue(FileInfo.FullName, "pwd", PassWord);
label5.Text = "配置成功!";
- 本文标题: C# 动态增删改App.Config,动态配置app.config
- 文章分类:【WinForm/WPF】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
- 上一篇:发布文章的时候产生错误日志:无效的视图状态
- 下一篇: C# 数据库连接是否正常测试