zoukankan      html  css  js  c++  java
  • C#下.NET配置文件的使用(1)

    原文链接:https://blog.csdn.net/dbzhang800/article/details/7212420

    System.Configuration 命名空间中的东西是为读写应用程序的配置数据服务的。

    在Windows早期,程序使用 .ini 作为配置文件,后来开始鼓励大家使用注册表,到了.NET中,又回归到使用文件,只不过这次默认是xml格式的文件。

    例子

     

     程序program.exe默认配置文件 program.exe.config 中的 "appSettings" 段

    读写 program.exe.config 中的 "appSettings" 段

    读写 program.exe.config 中的自定义字段 "QtSection"

    读写 roaming 文件中的自定义字段"QtSection"

    读写 任意位置的配置文件?

    例子一

    • 配置文件 program.exe.config
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
     <appSettings>
        <add key="first name" value="Debao" />
        <add key="last name" value="Zhang" />
     </appSettings>
    </configuration>
    • 程序源码 program.cs
    using System.Configuration;
    
    namespace DbZhang800
    {
        public class TestSettings
        {
            public static void Main()
            {
                foreach (string key in ConfigurationManager.AppSettings)
                {
                    string val = ConfigurationManager.AppSettings[key];
                    Console.WriteLine("{0}: {1}", key, val);
                }
            }
        }
    }

    编译运行,结果如下:

    E:> csc program.cs
    E:> program.exe
    first name: Debao
    last name: Zhang

    通过 ConfigurationManager.AppSettings 我们可以很方便地读取默认配置文件中的 appSettings 段。

    例子二

    前面是只读的,如果需要写入怎么办?

                Configuration appConf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                appConf.AppSettings.Settings.Add("Qt", "Quick");
                appConf.Save();

    编译运行(注,这是运行3次后的结果,每次都给Qt这个key增加了一项):

    E:> csc program.cs
    E:> program.exe
    first name: Debao
    last name: Zhang
    Qt: Quick,Quick,Quick

    此时的配置文件 program.exe.config 内容如下:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
     <appSettings>
         <add key="first name" value="Debao" />
         <add key="last name" value="Zhang" />
         <add key="Qt" value="Quick,Quick,Quick" />
     </appSettings>
    </configuration>

    例子三

    看看读写自定义字段的情况。不操作appSettings,操作一个自定义的QtSection段

    program.cs

    • 首先创建一个ConfigurationSection的派生类

    • 然后打开一个配置文件,通过该派生类进行操作
    using System;
    using System.Configuration;
    
    namespace DbZhang800
    {
        public sealed class QtSection : ConfigurationSection
        {
            [ConfigurationProperty("version", DefaultValue="4.4.0")]
            public string Version
            {
                get
                {
                    return (string)this["version"];
                }
    
                set
                {
                    this["version"] = value;
                }
            }
        }
    
        public class TestSettings
        {
            public static void Main()
            {
                Configuration appConf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                QtSection qtsection;
                if ((qtsection = (QtSection)appConf.Sections["QtSection"]) == null)
                {
                    qtsection = new QtSection();
                    //qtsection.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser;
                    appConf.Sections.Add("QtSection", qtsection);
                }
                Console.WriteLine("Current: {0}", qtsection.Version);
                qtsection.Version = "5.0.0";
                appConf.Save(ConfigurationSaveMode.Full);
            }
        }
    }

    运行后,生成的配置文件如下:

    program.exe.config

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
     <configSections>
         <section name="QtSection" type="DbZhang800.QtSection, Program, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="true" />
     </configSections>
     <QtSection version="5.0.0" />
    </configuration>

    注意:它在configSections自动添加了我们自定义段的一些信息。

    例子四

    前面的配置文件和应用程序在同一个目录下,如果不同用户需要不同的配置文件怎么办呢?

    前面的例子中,OpenExeConfiguration 使用的参数是 None,该参数指定不同的级别

    None

    只使用程序默认配置文件

    PerUserRoaming

    也要使用用户 roam 文件

    PerUserRoamingAndLocal

    也要使用用户local 文件

    在前一个例子基础上,我们把 None 改为 PerUserRoaming看看,结果... 运行时:

    E:TestSettings>program.exe
    Current: 5.0.0
    
    未处理的异常:  System.Configuration.ConfigurationErrorsException: 执行 !QtSection
     的配置节处理程序时出错。 ---> System.InvalidOperationException: 不能编辑已锁定的
     ConfigurationSection 属性。
    ...

    报出异常,无法将其写入到roaming文件,原因何在呢?

    • 就在于我们在xml文件看到的那个 MachineToApplication 属性,该段只能写入到machine和appplication级别的配置文件,无法写入用户配置文件。

    我们需要在生成这个段的时候就添加一个 MachineToRoamingUser 属性

           public static void Main()
            {
                Configuration appConf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
                QtSection qtsection;
                if ((qtsection = (QtSection)appConf.Sections["QtSection"]) == null)
                {
                    qtsection = new QtSection();
                    qtsection.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToRoamingUser;
                    appConf.Sections.Add("QtSection", qtsection);
                }
                Console.WriteLine("Current: {0}", qtsection.Version);
                qtsection.Version = "5.0.0";
                Console.WriteLine(appConf.FilePath);
                appConf.Save(ConfigurationSaveMode.Full);
            }

    这样,配置可以正常写入

    C:UsersdbzhangAppDataRoamingDbZhang800Program.exe_Url_foycvmvcbx4tf51hrft53z11fmpo2kto0.0.0.0user.config

    打开其他的配置文件:

    • ConfigurationManager.OpenExeConfiguration(string)

      • 这个东西,string 指定 exe 的路径(但不限于,该路径后会被自动添加一个 .config)
    • ConfigurationManager..::.OpenMachineConfiguration()

      • 位于%windir%Microsoft.NETFrameworkversionconfig

    例子五

    操作其他的配置文件

    比如,我要操作当前工作目录下的 abcd.config 这个文件,那么需要使用 OpenMappedExcConfiguration:

            public static void Main()
            {
                string path = System.IO.Path.Combine(Environment.CurrentDirectory, "abcd.config");
                ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
                configFile.ExeConfigFilename = path;
                Configuration appConf = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
    
                QtSection qtsection;
                if ((qtsection = (QtSection)appConf.Sections["QtSection"]) == null)
                {
                    qtsection = new QtSection();
                    appConf.Sections.Add("QtSection", qtsection);
                }
                Console.WriteLine("Current: {0}", qtsection.Version);
                qtsection.Version = "5.0.0";
                appConf.Save(ConfigurationSaveMode.Full);
           }
  • 相关阅读:
    WEB前端开发规范文档
    js九九乘法表
    阿里前端两年随想
    自动播放选项卡
    HTML+CSS编写规范
    简易秒表
    关于响应式布局
    关于PHP语言
    关于CSS3的小知识点之2D变换
    关于H5框架之Bootstrap的小知识
  • 原文地址:https://www.cnblogs.com/runningRain/p/13825718.html
Copyright © 2011-2022 走看看