winform开发中对App.Config的写和读操作

xiaomiao001 2009-11-05 08:59:36
我是想在App.Config存储数据库的连接信息,App.Config文件的内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Server" value="."/>
<add key="Database" value="meter"/>
<add key="Uid" value="sa"/>
<add key="Pwd" value="sa"/>
</appSettings>
</configuration>

开发环境:vs2008;
开发语言:C#。

现在我做了一个窗体,要对App.Config进行读和改操作,请各位大侠不吝赐教!
感激涕零!
...全文
876 29 打赏 收藏 转发到动态 举报
写回复
用AI写文章
29 条回复
切换为时间正序
请发表友善的回复…
发表回复
lovelan1748 2009-11-06
  • 打赏
  • 举报
回复
Form里有Configuration
nashina 2009-11-06
  • 打赏
  • 举报
回复
[Quote=引用 22 楼 angel6709 的回复:]
我晕::::

引入System.Configuration

ConfigurationManager.AppSettings[strKey];


[/Quote]


你这个应该是ASP.NET里的用法;
我在winform都是自己来操作xml文件的
Jave.Lin 2009-11-06
  • 打赏
  • 举报
回复
没怎么用过。

但都是XML文件,就操作XML就可以了。

顶下。
龙宜坡 2009-11-06
  • 打赏
  • 举报
回复
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Web;
using System.Reflection;

namespace Common
{
/// <summary>
/// 配置文件类型,是WinForm还是WebForm
/// </summary>
public enum ConfigFileType
{
WebConfig,
AppConfig
}
/// <summary>
/// 对AppSettings节点进行增加,删除,修改操作.
/// </summary>
public class AppSettingsHelper
{
public static string docName = String.Empty;
private static XmlNode node = null;


/// <summary>
/// 设置节点的值,若该节点不存在,则创建一个新的节点。
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="cfgType"></param>
/// <returns></returns>
public static bool SetValue(string key, string value, ConfigFileType cfgType)
{
XmlDocument cfgDoc = new XmlDocument();
loadConfigDoc(cfgDoc, cfgType);
// retrieve the appSettings node
node = cfgDoc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new InvalidOperationException("appSettings section not found");
}
try
{
// XPath select setting "add" element that contains this key
XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (addElem != null)
{
addElem.SetAttribute("value", value);
}
// not found, so we need to add the element, key and value
else
{
XmlElement entry = cfgDoc.CreateElement("add");
entry.SetAttribute("key", key);
entry.SetAttribute("value", value);
node.AppendChild(entry);
}
//save it
saveConfigDoc(cfgDoc, docName);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 获取节点的值
/// </summary>
/// <param name="key"></param>
/// <param name="cfgType"></param>
/// <returns></returns>
public static string GetValue(string key, ConfigFileType cfgType)
{
XmlDocument cfgDoc = new XmlDocument();
loadConfigDoc(cfgDoc, cfgType);
// retrieve the appSettings node
node = cfgDoc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new InvalidOperationException("appSettings section not found");
}

// XPath select setting "add" element that contains this key
XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (addElem != null)
{

return addElem.GetAttribute("value");
}
// not found, so we need to add the element, key and value
else
{
throw new ArgumentException(string.Format("key '{0}' not found", key));
}


}


private static void saveConfigDoc(XmlDocument cfgDoc, string cfgDocPath)
{
try
{
XmlTextWriter writer = new XmlTextWriter(cfgDocPath, null);
writer.Formatting = Formatting.Indented;
cfgDoc.WriteTo(writer);
writer.Flush();
writer.Close();
return;
}
catch
{
throw;
}
}



/// <summary>
/// 移除节点
/// </summary>
/// <param name="elementKey"></param>
/// <param name="cfgType"></param>
/// <returns></returns>
public static bool RemoveElement(string elementKey, ConfigFileType cfgType)
{
try
{
XmlDocument cfgDoc = new XmlDocument();
loadConfigDoc(cfgDoc, cfgType);
// retrieve the appSettings node
node = cfgDoc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new InvalidOperationException("appSettings section not found");
}
// XPath select setting "add" element that contains this key to remove
node.RemoveChild(node.SelectSingleNode("//add[@key='" + elementKey + "']"));
saveConfigDoc(cfgDoc, docName);
return true;
}
catch
{
return false;
}
}


/// <summary>
/// 修改节点的值
/// </summary>
/// <param name="elementKey"></param>
/// <param name="cfgType"></param>
/// <returns></returns>
public static bool ModifyElement(string elementKey, ConfigFileType cfgType)
{
try
{
XmlDocument cfgDoc = new XmlDocument();
loadConfigDoc(cfgDoc, cfgType);
// retrieve the appSettings node
node = cfgDoc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new InvalidOperationException("appSettings section not found");
}
// XPath select setting "add" element that contains this key to remove
node.RemoveChild(node.SelectSingleNode("//add[@key='" + elementKey + "']"));
saveConfigDoc(cfgDoc, docName);
return true;
}
catch
{
return false;
}
}



private static XmlDocument loadConfigDoc(XmlDocument cfgDoc, ConfigFileType cfgType)
{
// load the config file
if (cfgType == ConfigFileType.AppConfig)
{
docName = ((Assembly.GetEntryAssembly()).GetName()).Name;
docName += ".exe.config";
}
else
{
docName = HttpContext.Current.Server.MapPath("web.config");
}
cfgDoc.Load(docName);
return cfgDoc;
}

}
}
angel6709 2009-11-06
  • 打赏
  • 举报
回复
我晕::::

引入System.Configuration

ConfigurationManager.AppSettings[strKey];

nashina 2009-11-06
  • 打赏
  • 举报
回复
把它当做xml文件处理就行了;
利用xml文件的读写方法来实现;
如果不知道xml操作的话可以上网查下,如果需要的话给我留个言,给你发个完整的例子
chengxiaorong 2009-11-06
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 wodegege10 的回复:]
C# code///<summary>/// 文件配置类///</summary>class Config {static Config _ins;///<summary>/// 配置单例///</summary>internalstatic Config Ins {get {if (_ins==null) {
_ins=new Config();
?-
[/Quote]挺好
black1022 2009-11-06
  • 打赏
  • 举报
回复
学学对XML的操作自己写个类。

/// <summary>
/// 修改对应节点的值
/// </summary>
/// <param name="filepath">文件路径</param>
/// <param name="NodeString">节点串(configuration/appSettings/add)</param>
/// <param name="KeyName1">节点属性名(key)</param>
/// <param name="KeyValue1">节点属性名对应的值("Server")</param>
/// <param name="KeyName2">要修改的节点属性名(value)</param>
/// <param name="KeyValue2">要修改的节点属性名的值("."是原来的值可以改为对应的参数)</param>
public void ChangeXmlNodeValue(string filepath, string NodeString, string KeyName1, string KeyValue1, string KeyName2, string KeyValue2)
{
XmlDocument xml = new XmlDocument();
try
{
xml.Load(filepath);
XmlElement root = xml.DocumentElement;
XmlNodeList rnl = root.SelectNodes(NodeString);
foreach (XmlNode xnd in rnl)
{
if (xnd.Attributes[KeyName1].Value == KeyValue1)
{
xnd.Attributes[KeyName2].Value = KeyValue2;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
wartim 2009-11-06
  • 打赏
  • 举报
回复
批量改

Configuration C=ConfigurationManager.OpenExeConfiguration(String .Empty);
C.AppSettings.Settings["Server"].Value = "192.168.1.11";
C.AppSettings.Settings["Database"].Value = "aaa";
C.AppSettings.Settings["Uid"].Value = "sa";
C.AppSettings.Settings["Pwd"].Value = "123";
C.Save(ConfigurationSaveMode.Modified);


xiaomiao001 2009-11-06
  • 打赏
  • 举报
回复
[Quote=引用 15 楼 wartim 的回复:]
不需要点击保存,直接就改了
[/Quote]
不懂!
flyerwing 2009-11-06
  • 打赏
  • 举报
回复
return ConfigurationManager.AppSettings[strKey];

这样好象方便
wartim 2009-11-06
  • 打赏
  • 举报
回复
不需要点击保存,直接就改了
xiaomiao001 2009-11-06
  • 打赏
  • 举报
回复
接着顶!
幸运的意外 2009-11-06
  • 打赏
  • 举报
回复
System.Configuration.ConfigurationSettings.AppSettings["键值名"]这个属性是个可读写的,如果读取就直接用个string变量接收,如果是赋值那么直接让它等于键值就行了.
string getValue = System.Configuration.ConfigurationSettings.AppSettings["Uid"];
System.Configuration.ConfigurationSettings.AppSettings["Uid"] = "New123";
Brian_wh 2009-11-06
  • 打赏
  • 举报
回复
using System.Configuration;
//读取
string Server = System.Configuration.ConfigurationManager.AppSettings["Server"].ToString();
string Database = System.Configuration.ConfigurationManager.AppSettings["Database"].ToString();
……
//写入
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;

app.Settings["Server"].Value = "Value";
app.Settings["Database"].Value = "Value";
……
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
MrYoung 2009-11-06
  • 打赏
  • 举报
回复
1 在应用程序里添加app.config

<?xml version="1.0" encoding="utf-8" ?><configuration><appSettings><!-- User application and configured property settings go here.--> <!-- Example: <add key="settingName" value="settingValue"/> --> <add key="ServerIP" value="127.0.0.1"/> <add key="Server" value="Automation_temp"></add> <add key="user" value="sa"></add> <add key="password" value="shan"></add></appSettings></configuration>

程序读取数据库连接,如下:
如果想把连接的信息显示出来,可以去解析字符串strcon,获取相关信息
private void Open() { // open connection if (con == null) { string strcon=String.Format ("packet size=4096;data source={0};persist security info=True;initial catalog={1};user id={2};password={3}",ConfigurationSettings.AppSettings["SQLserverIP"], ConfigurationSettings.AppSettings["Server"],ConfigurationSettings.AppSettings["user"],ConfigurationSettings.AppSettings["password"]); con = new SqlConnection(strcon); try { con.Open(); } catch(Exception ee) { ee.ToString(); } } }

2 新建窗体ConfigFrm
添加4个label ,分别是:
服务器ip,Database Name,SA,password,
4个TextBox,分别是:
txtIP
txtDataBaseName
txtName
txtPwd
1个确认按钮btnOK,
3 写个方法保存修改的设置:

private void SaveConfig(string ConnenctionString,string strKey) { XmlDocument doc=new XmlDocument(); //获得配置文件的全路径 string strFileName=AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; doc.Load(strFileName); //找出名称为“add”的所有元素 XmlNodeList nodes=doc.GetElementsByTagName("add"); for(int i=0;i<nodes.Count;i++) { //获得将当前元素的key属性 XmlAttribute att=nodes[i].Attributes["key"]; //根据元素的第一个属性来判断当前的元素是不是目标元素 if (att.Value==strKey) { //对目标元素中的第二个属性赋值 att=nodes[i].Attributes["value"]; att.Value=ConnenctionString; break; } } //保存上面的修改 doc.Save(strFileName); }

4 在确认按钮btnOK click事件:

private void btnOK_Click(object sender, System.EventArgs e) { if (txtIP.Text=="") { MessageBox.Show("ServerIP is not allow null"); return ; } else if(txtDataBaseName.Text=="") { MessageBox.Show("DataBase is not allow null"); return ; } else if(txtName.Text=="") { MessageBox.Show("User Name is not allow null"); return ; } else { SaveConfig(txtIP.Text,"ServerIP"); SaveConfig(txtDataBaseName.Text,"Server"); SaveConfig(txtName.Text,"user"); SaveConfig(txtPassword.Text,"password"); MessageBox.Show("Config Sucessful!","",MessageBoxButtons.OK,MessageBoxIcon.Warning); } this.Close(); }
在应用程序当前目录下,程序动态加载的是 /bin/debug/test.exe.config信息,从而实现了动态读写xml文件,去获取
数据库连接。
xiaomiao001 2009-11-05
  • 打赏
  • 举报
回复
再顶!
xiaomiao001 2009-11-05
  • 打赏
  • 举报
回复
[Quote=引用 11 楼 shenmixiaozi 的回复:]
System.Configuration.ConfigurationSettings.AppSettings["Server"] System.Configuration.ConfigurationSettings.AppSettings["Database"]
System.Configuration.ConfigurationSettings.AppSettings["Uid"]
System.Configuration.ConfigurationSettings.AppSettings["Pwd"]

[/Quote]

那点击“保存”的时候呢?如何将修改App.Config文件?
shenmixiaozi 2009-11-05
  • 打赏
  • 举报
回复
System.Configuration.ConfigurationSettings.AppSettings["Server"] System.Configuration.ConfigurationSettings.AppSettings["Database"]
System.Configuration.ConfigurationSettings.AppSettings["Uid"]
System.Configuration.ConfigurationSettings.AppSettings["Pwd"]
xiaomiao001 2009-11-05
  • 打赏
  • 举报
回复
能写一个我可以直接用的吗?
加载更多回复(9)

110,545

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧