博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于app.config不能即时保存读取的解决方案
阅读量:2437 次
发布时间:2019-05-10

本文共 1620 字,大约阅读时间需要 5 分钟。

public
void
saveValue(
string
Name,
string
Value)
{
    
ConfigurationManager.AppSettings.Set(Name, Value);
    
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    
config.AppSettings.Settings[Name].Value = Value;
    
config.Save(ConfigurationSaveMode.Modified);
    
config =
null
;
}

用上面的函数总是等到程序运行结束,才将数据保存进去。

所以我们换了一种方式,以xml的方式进行保存及读取。直接上代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public
static
void
SetAppConfig(
string
appKey,
string
appValue)
{
    
XmlDocument xDoc =
new
XmlDocument();
    
xDoc.Load(System.Windows.Forms.Application.ExecutablePath +
".config"
);
 
    
var
xNode = xDoc.SelectSingleNode(
"//appSettings"
);
 
    
var
xElem = (XmlElement)xNode.SelectSingleNode(
"//add[@key='"
+ appKey +
"']"
);
    
if
(xElem !=
null
) xElem.SetAttribute(
"value"
, appValue);
    
else
    
{
        
var
xNewElem = xDoc.CreateElement(
"add"
);
        
xNewElem.SetAttribute(
"key"
, appKey);
        
xNewElem.SetAttribute(
"value"
, appValue);
        
xNode.AppendChild(xNewElem);
    
}
    
xDoc.Save(System.Windows.Forms.Application.ExecutablePath +
".config"
);
}
 
public
static
string
GetAppConfig(
string
appKey)
{
    
XmlDocument xDoc =
new
XmlDocument();
    
xDoc.Load(System.Windows.Forms.Application.ExecutablePath +
".config"
);
 
    
var
xNode = xDoc.SelectSingleNode(
"//appSettings"
);
 
    
var
xElem = (XmlElement)xNode.SelectSingleNode(
"//add[@key='"
+ appKey +
"']"
);
 
    
if
(xElem !=
null
)
    
{
        
return
xElem.Attributes[
"value"
].Value;
    
}
    
return
string
.Empty;
}

使用方式

设置

SetAppConfig("SourceDBIP", txtSourceAddress.Text.Trim());

读取

Setting.GetAppConfig("SourceDBIP")

转载自https://www.cnblogs.com/homezzm/p/3580079.html

你可能感兴趣的文章
malloc的小知识
查看>>
UVALive 6755 - Swyper Keyboard
查看>>
uva10023 手算开方的方法
查看>>
第一个JSP程序(JSP入门)
查看>>
JSP语法简介
查看>>
JSP中EL表达式入门与简介
查看>>
Spring的几种注入方式
查看>>
Spring自动装配
查看>>
Hibernate入门与实例
查看>>
Jython入门学习
查看>>
Hiberate基础用法实例
查看>>
Maven编译时指定JDK版本
查看>>
Hibernate单向关联N-1
查看>>
Hibernate单向关联1-1
查看>>
jQuery自定义动画
查看>>
Spring-data-redis在shiro中的实例
查看>>
GUN C中__attribute__作用
查看>>
3、系统调用之SYSCALL_DEFINE分析
查看>>
linux的signal_pending及signal
查看>>
OBJDUMP用法
查看>>