转自:http://www.cnblogs.com/xiaof2000/archive/2009/12/16/1625198.html
初用.net 2008,想写个数据库设置工作设置数据库连接,在另一程序中读取设置信息。本来简单的事结果……。
有人说的.net 的bug,有人用.net 1.0的办法……
找了许多资料,也不会用settings.settings,但终于简单的解决了。
代码如下:
两个程序共享的app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings >
<add key ="teststring" value ="testnnnn"/>
</appSettings>
</configuration>
首先要先在项目中引用System.Configuration 这个文件,然后再用using System.Configuration 进行引用,不然找不到ConfigurationManager 这个类。
设置数据库连接的程序(demo_setup.exe)代码:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["teststring"].Value="ddd";
config.Save();
设置数据库连接的程序(demo_setup.exe)读取代码:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
textBox1.Text = config.AppSettings.Settings["DemoData"].Value.ToString();
---------------------------------
另一程序(demo.exe)中,读取非本程序的app.config 的代码
Configuration config = ConfigurationManager.OpenExeConfiguration(@"C:\demo_seup.exe");
textBox1.Text = config.AppSettings.Settings["DemoData"].Value.ToString();