会员
周边
众包
新闻
博问
闪存
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
新视野 新选择——Kevin Lin's Blog
博客园
首页
新随笔
联系
订阅
管理
以前vs03项目中用到一个类:读写config文件配置信息
using
System;
using
System.Xml;
using
System.IO;
namespace
DataManager
{
/**/
///
<summary>
///
修改和读取上传属性的方法
///
</summary>
public
class
Config
{
private
string
fileName
=
""
;
private
XmlDocument xmlDoc
=
new
XmlDocument();
private
XmlNode appnode
=
null
;
public
Config(
string
filePath)
{
fileName
=
filePath;
xmlDoc.Load(fileName);
XmlElement root
=
xmlDoc.DocumentElement;
for
(
int
i
=
0
; i
<
root.ChildNodes.Count; i
++
)
{
if
(root.ChildNodes[i].Name.ToLower()
==
"
appsettings
"
)
{
appnode
=
root.ChildNodes[i];
break
;
}
}
}
写 void SetConfig(string key, string Value)
#region
写 void SetConfig(string key, string Value)
/**/
///
<summary>
///
写
///
</summary>
///
<param name="key"></param>
///
<param name="Value"></param>
public
void
SetConfig(
string
key,
string
Value)
{
bool
blnFound
=
false
;
key
=
key.ToLower();
foreach
(XmlNode node
in
appnode.ChildNodes)
{
if
(node.Name.ToLower()
==
"
add
"
)
{
if
(node.Attributes.GetNamedItem(
"
key
"
).Value.ToLower()
==
key)
{
node.Attributes.GetNamedItem(
"
value
"
).Value
=
Value;
blnFound
=
true
;
break
;
}
}
}
if
(
!
blnFound)
{
XmlNode childnode
=
xmlDoc.CreateNode(XmlNodeType.Element,
"
add
"
,
""
);
XmlAttribute attr ;
attr
=
xmlDoc.CreateAttribute(
"
key
"
);
attr.Value
=
key;
childnode.Attributes.Append(attr);
attr
=
xmlDoc.CreateAttribute(
"
value
"
);
attr.Value
=
Value;
childnode.Attributes.Append(attr);
appnode.AppendChild(childnode);
}
xmlDoc.Save(fileName);
}
#endregion
读string GetConfig(string key)
#region
读string GetConfig(string key)
/**/
///
<summary>
///
读
///
</summary>
///
<param name="key"></param>
public
string
GetConfig(
string
key)
{
string
noteValue
=
""
;
key
=
key.ToLower();
foreach
(XmlNode node
in
appnode.ChildNodes)
{
if
(node.Name.ToLower()
==
"
add
"
)
{
if
(node.Attributes.GetNamedItem(
"
key
"
).Value.ToLower()
==
key)
{
noteValue
=
node.Attributes.GetNamedItem(
"
value
"
).Value;
break
;
}
}
}
return
noteValue;
}
#endregion
}
}
对应的config文件为:
<?
xml version
=
"
1.0
"
encoding
=
"
utf-8
"
?>
<
configuration
>
<
appSettings
>
<
add key
=
"
key1
"
value
=
"
1
"
/>
<
add key
=
"
key2
"
value
=
"
0
"
/>
</
appSettings
>
</
configuration
>
应用示例如下:
Config cf
=
new
Config(Application.ExecutablePath
+
"
.config
"
);
string
key1Value
=
cf.GetConfig(
"
key1
"
);
//get
key1Value
+=
"
key1 has been Edited
"
;
cf.SetConfig(
"
key1
"
, key1Value);
//set
现在VS2005当然也可以用,不过05提供了更好的读写方法~
posted @
2007-04-05 14:08
Kevin Lin
阅读(
588
) 评论(
1
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部
公告