码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2014-11-04 01:25:18      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   os   使用   for   sp   

对于桌面应用程序,常常会需要记录一些用户配置信息,早期的做法一般是使用读写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类型,可读写。
如图:

bubuko.com,布布扣


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 配置文件中。

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

标签:style   blog   http   io   ar   os   使用   for   sp   

原文地址:http://www.cnblogs.com/alanjl/p/4072569.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!