如何使用DotNet 2.0中的应用程序配置 Settings.settings

对于桌面应用程序,常常会需要记录一些用户配置信息,早期的做法一般是使用读写INI文件的办法。
    对于.NET应用程序,并没有提供直接操作INI文件的类,需要调用Win32API,具体办法可以参考:
http://www.blogcn.com/user52/seabluescn/blog/23969537.html 可以看到这种办法比较麻烦。

    随着.NET Framerwork 2.0 的出现,对应用程序设置提供了内在的支持,现在读写配置信息要简单方便得多了。

1.新建工程,打开Properties\Settings.settings  名称,类型,值,都不要说,一看就明白,唯一要讲的是范围,
Application:程序设置,只读;
Uesr:用户配置属性:可读写。
我们建两个配置属性,"ConnStr":String类型,只读;Left:uint类型,可读写。
如图:


2.现在就可以使用这两个配置属性了:

 
        /// <summary>
        /// 读取数据
        /// </summary>
        private void btnRead_Click(object sender, EventArgs e)
        {
            string connstr = WindowsApplication1.Properties.Settings.Default.ConnStr;
            MessageBox.Show(connstr);
        }

        /// <summary>
        /// 存入数据
        /// </summary>
        private void btnSet_Click(object sender, EventArgs e)
        {


            uint s = 123;
            WindowsApplication1.Properties.Settings.Default.Left = s;
            WindowsApplication1.Properties.Settings.Default.Save();
        }

3.程序目录下会有一个WindowsApplication1.exe.config的文件,可以直接修改该文件,以改变配置。

4.对于用户配置属性(user),其修改值并不是保存在WindowsApplication1.exe.config文件内,而是保持在C:\Documents and Settings目录下,WindowsApplication1.exe.config文件保持的是程序读取配置失败时的默认值。而对于应用程序配置属性(Application),其值直接保存在WindowsApplication1.exe.config文件内(只读)。

 

 

 

//string ConnStr = tang.Properties.Settings.Default.ConnStr;
           // string ConnStr = Properties.Settings.Default["ConnStr"].ToString();
          //  string ConnStr = ConfigurationManager.AppSettings["ConnStr"];

//ConfigurationManager这种办法需要添加引用DLL System.Configuration

           // int aa = Convert.ToInt32(Properties.Settings.Default.Left);
          //  Console.WriteLine(aa);

 

 

1、定义

在Settings.settings文件中定义配置字段。把作用范围定义为:User则运行时可更改,Applicatiion则运行时不可更改。可以使用数据网格视图,很方便;

2、读取配置值

text1.text = Properties.Settings.Default.FieldName;
//FieldName是你定义的字段

3、修改和保存配置

Properties.Settings.Default.FieldName = "server";

Properties.Settings.Default.Save();//使用Save方法保存更改

注意:当设置scope为User时他的配置放在 C:\Documents and Settings\LocalService\Local Settings\Application Data\在这个目录下或子目录user.config 配置文件中。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。