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.新建工程,打开PropertiesSettings.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 SettingsLocalServiceLocal SettingsApplication Data在这个目录下或子目录user.config 配置文件中。

    Top
    收藏
    关注
    评论
  • 相关阅读:
    【Spring注解驱动开发】你了解@PostConstruct注解和@PreDestroy注解吗?
    【Spring注解驱动开发】使用InitializingBean和DisposableBean来管理bean的生命周期,你真的了解吗?
    【Spring注解驱动开发】如何使用@Bean注解指定初始化和销毁的方法?看这一篇就够了!!
    【分布式事务】如何基于消息中间件实现分布式事务?万字长文给你答案!!
    【K8S】Kubernetes中暴露外部IP地址来访问集群中的应用
    【K8S】Service服务详解,看这一篇就够了!!
    【Spring注解驱动开发】面试官让我说说:如何使用FactoryBean向Spring容器中注册bean?
    【K8S】如何进入kubernetes的一个pod
    这是对我最大的认可和鼓励
    我的价值观
  • 原文地址:https://www.cnblogs.com/alanjl/p/4072569.html
Copyright © 2011-2022 走看看