zoukankan      html  css  js  c++  java
  • 如何使用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 配置文件中。

  • 相关阅读:
    MySQL数据库初识
    Python中面向对象初识到进阶
    python 函数进阶
    Python 函数的初识
    Python的发展与应用
    什么是产品经理 以及职责
    I/O----复制文本文件
    获取次日日期(主要两种方法)
    vector以及array和数组
    编辑软件注释快捷键
  • 原文地址:https://www.cnblogs.com/wangs/p/1942044.html
Copyright © 2011-2022 走看看