您的当前位置:首页正文

App.config和配置文件的读写

2020-02-04 来源:客趣旅游网
App.config和配置文件的读写

主要用来读取数据库连接,当然也可以设置其他项,废话不多说看代码

using System;

using System.Collections.Generic; using System.Text;

using System.Configuration; using System.Collections; using System.Xml;

using System.Windows.Forms;

namespace Windo {

class AppClass1 {

// GetConfiguration#region GetConfiguration /**/

///

/// 取得appSettings里的值 ///

/// 键 ///

public static string GetConfiguration(string key) {

return ConfigurationSettings.AppSettings[key]; }

public static string GetConfigValue() {

string conn;

XmlDocument xDoc = new XmlDocument(); try {

//加载app.config文件

//xDoc.Load(Application.ExecutablePath + \".config\"); //这个读取的是:项目名.exe.config文件

xDoc.Load(\"D:\\\\Demo\\\\Windo\\\\Windo\\\\Windo\\\\app.config\"); //这里是读取app.config文件

//寻找add元素 XmlElement xElem1 =

(XmlElement)xDoc.SelectSingleNode(\"/configuration/connectionStrings/add\"); if (xElem1 != null) {

//返回add元素中connectionString属性值

conn = xElem1.GetAttribute(\"connectionString\");

// MessageBox.Show(xElem1.GetAttribute(\"connectionString\")); return conn; }

return conn = \"读取错误!\"; }

catch (Exception) {

conn = \"读取错误!\"; return conn; } }

public static string GetConfigString(string key) { //

// TODO: 在此处添加构造函数逻辑 //

return ConfigurationSettings.AppSettings[key]; }

//写操作

public void SetValue(string AppKey, string AppValue) {

XmlDocument xDoc = new XmlDocument(); //获取可执行文件的路径和名称

xDoc.Load(System.Windows.Forms.Application.ExecutablePath + \".config\");

XmlNode xNode; XmlElement xElem1; XmlElement xElem2;

xNode = xDoc.SelectSingleNode(\"//appSettings\");

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(System.Windows.Forms.Application.ExecutablePath + \".config\"); }

}

//////

///

/// 没啥用,狗头军师老出错。 ///

public class AppConfig {

private XmlDocument Doc = new XmlDocument(); private AppDomain Ad = AppDomain.CurrentDomain; public AppConfig() {

Doc.Load(Ad.SetupInformation.ConfigurationFile); }

public void LoadAppConfig() {

Doc.Load(Ad.SetupInformation.ConfigurationFile); }

public void SetAppValue(string key, string newValue) {

Doc.SelectSingleNode(\"/configuration/appSettings/add[@key='\" + key + \"']\").Attributes[\"value\"].Value = newValue; }

public void SaveAppConfig() {

Doc.Save(Ad.SetupInformation.ConfigurationFile); Doc.Load(Ad.SetupInformation.ConfigurationFile); }

public string GetAppValue(string key) {

return Doc.SelectSingleNode(\"/configuration/appSettings/add[@key='\" + key + \"']\").Attributes[\"value\"].Value;

//return Doc.SelectSingleNode(\"/configuration/connectionStrings/add[@key='\" + key + \"']\").Attributes[\"value\"].Value; }

///////////////////// } }

因篇幅问题不能全部显示,请点此查看更多更全内容