• (转)Config配置文件的操作


    1. 创建配置节类

    必须创建继承自ConfigurationSection的对象才能进行配置数据读写操作, ConfigurationSection提供了索引器用来获取和设置配置数据,需要注意的是拥有ConfigurationProperty特性的属性 才会被存储,并且名称要保持大小写完全一致,如下面的代码中,所有的"id"必须保持一样。

    class ConfigSectionData : ConfigurationSection

    {

    [ConfigurationProperty("id")]

    public int Id

    {

    get { return (int)this["id"]; }

    set { this["id"] = value; }

    }

    [ConfigurationProperty("time")]

    public DateTime Time

    {

    get { return (DateTime)this["time"]; }

    set { this["time"] = value; }

    }

    }

    2. 创建配置文件操作对象

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    ConfigSectionData data = new ConfigSectionData();

    data.Id = 1000;

    data.Time = DateTime.Now;

    config.Sections.Add("add", data);

    config.Save(ConfigurationSaveMode.Minimal);

    上面的例子是操作 app.config,在根节点(configuration)下写入名称为"add"的配置数据。

    <?xml version="1.0" encoding="utf-8" ?>

    <configuration>

    <configSections>

    <section name="add" type="ConsoleApplication1.ConfigSectionData, ... />

    </configSections>

    <add id="1000" time="02/18/2006 21:51:06" />

    </configuration>

    需要注意的 VS2005 在IDE模式下会将信息写入 *.vshost.exe.config,并且在程序关闭时覆写该文件,因此您可能看不到您写入的配置数据,只要在资源管理其中执行 *.exe 文件,您就可以在 *.exe.config 文件中看到结果了。

    如果我们需要操作非缺省配置文件,可以使用ExeConfigurationFileMap对象。

    ExeConfigurationFileMap file = new ExeConfigurationFileMap();

    file.ExeConfigFilename = "test.config";

    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);

    ConfigSectionData data = new ConfigSectionData();

    data.Id = 1000;

    data.Time = DateTime.Now;

    config.Sections.Add("add", data);

    config.Save(ConfigurationSaveMode.Minimal);

    如果我们不希望在根节点下写入配置数据,可以使用ConfigurationSectionGroup对象。

    ExeConfigurationFileMap file = new ExeConfigurationFileMap();

    file.ExeConfigFilename = "test.config";

    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);

    ConfigSectionData data = new ConfigSectionData();

    data.Id = 1000;

    data.Time = DateTime.Now;

    config.SectionGroups.Add("group1", new ConfigurationSectionGroup());

    config.SectionGroups["group1"].Sections.Add("add", data);

    config.Save(ConfigurationSaveMode.Minimal);

    下面就是生成的配置文件。

    <?xml version="1.0" encoding="utf-8"?>

    <configuration>

    <configSections>

    <sectionGroup name="group1" type="System.Configuration.ConfigurationSectionGroup, ... >

    <section name="add" type="ConsoleApplication1.ConfigSectionData, ... />

    </sectionGroup>

    </configSections>

    <group1>

    <add id="1000" time="02/18/2006 22:01:02" />

    </group1>

    </configuration>

    3. 读取配置文件

    ExeConfigurationFileMap file = new ExeConfigurationFileMap();

    file.ExeConfigFilename = "test.config";

    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);

    ConfigSectionData data = config.SectionGroups["group1"].Sections["add"] as ConfigSectionData;

    //ConfigSectionData data = config.Sections["add"] as ConfigSectionData; // 从根节读取

    if (data != null)

    {

    Console.WriteLine(data.Id);

    Console.WriteLine(data.Time);

    }

    4. 写配置文件

    在写入 ConfigurationSectionGroup 和 ConfigurationSection 前要判断同名配置是否已经存在,否则会写入失败。

    另外如果配置文件被其他Configuration对象修改,则保存会失败,并抛出异常。建议采用Singleton模式。

    ExeConfigurationFileMap file = new ExeConfigurationFileMap();

    file.ExeConfigFilename = "test.config";

    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);

    ConfigSectionData data = new ConfigSectionData();

    data.Id = 2000;

    data.Time = DateTime.Now;

    ConfigurationSectionGroup group1 = config.SectionGroups["group1"];

    if (group1 == null)

    config.SectionGroups.Add("group1", new ConfigurationSectionGroup());

    ConfigurationSection data = group1.Sections["add"] as config;

    if (add == null)

    config.SectionGroups["group1"].Sections.Add("add", data);

    else

    {

    group1.Sections.Remove("add");

    group1.Sections.Add("add", data);

    // 或者直接修改原配置对象,前提是类型转换要成功。

    //ConfigSectionData configData = add as ConfigSectionData;

    //configData.Id = data.Id;

    //configData.Time = data.Time;

    }

    config.Save(ConfigurationSaveMode.Minimal);

    5. 删除配置节

    删除ConfigurationSectionGroup

    config.SectionGroups.Remove("group1");

    //config.SectionGroups.Clear();

    config.Save(ConfigurationSaveMode.Minimal);

    删除ConfigurationSection

    config.Sections.Remove("add1");

    //config.Sections.Clear();

    if (config.SectionGroups["group1"] != null)

    {

    config.SectionGroups["group1"].Sections.Remove("add2");

    //config.SectionGroups["group1"].Sections.Clear();

    }

    config.Save(ConfigurationSaveMode.Minimal);

    6. 其他

    可以使用 ConfigurationManager.OpenMachineConfiguration() 来操作 Machine.config 文件。

    或者使用 System.Web.Configuration 名字空间中的 WebConfigurationManager 类来操作 ASP.NET 配置文件。

    ConfigurationManager还提供了AppSettings、ConnectionStrings、GetSection()等便捷操作。

    7. 使用自定义类

    比如ConfigSectionData里面

    除了简单类型之外,可不可以有自定义的类

    可以使用自定义类,不过需要定义一个转换器。

    using System;

    using System.Collections;

    using System.Collections.Generic;

    using System.Configuration;

    using System.Globalization;

    using System.ComponentModel;

    // 要写入配置文件的自定义类

    class CustomData

    {

    public CustomData(string s)

    {

    this.s = s;

    }

    private string s;

    public string S

    {

    get { return s; }

    set { s = value; }

    }

    }

    // 自定义的转换器(演示代码省略了类型判断)

    class CustomConvert : ConfigurationConverterBase

    {

    public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type type)

    {

    return (type == typeof(string));

    }

    public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)

    {

    return (value as CustomData).S;

    }

    public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data)

    {

    return new CustomData((string)data);;

    }

    }

    class ConfigSectionData : ConfigurationSection

    {

    [ConfigurationProperty("id")]

    public int Id

    {

    get { return (int)this["id"]; }

    set { this["id"] = value; }

    }

    [ConfigurationProperty("time")]

    public DateTime Time

    {

    get { return (DateTime)this["time"]; }

    set { this["time"] = value; }

    }

    [ConfigurationProperty("custom")]

    [TypeConverter(typeof(CustomConvert))] // 指定转换器

    public CustomData Custom

    {

    get { return (CustomData)this["custom"]; }

    set { this["custom"] = value; }

    }

    }

    public class Program

    {

    static void Main(string[] args)

    {

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    ConfigSectionData data = new ConfigSectionData();

    data.Id = 1000;

    data.Time = DateTime.Now;

    data.Custom = new CustomData("abcdefg...");

    config.Sections.Add("add", data);

    config.Save(ConfigurationSaveMode.Minimal);

    // 读取测试

    ConfigSectionData configData = (ConfigSectionData)config.Sections["add"];

    Console.WriteLine(configData.Custom.S);

    }

    }

    保存后的配置文件

    <?xml version="1.0" encoding="utf-8" ?>

    <configuration>

    <configSections>

    <section name="add" type="..." />

    </configSections>

    <add id="1000" time="04/17/2006 22:06:58" custom="abcdefg..." />

    </configuration>

  • 相关阅读:
    转:SQL 操作结果集 -并集、差集、交集、结果集排序
    转:JSON 获取属性值的方法
    Could not find a getter for orderItems in class
    转:ServletContext,ActionContext,ServletActionContext
    Could not parse mapping document from input stream hibernate配置异常
    According to TLD or attribute directive in tag file, attribute test does not accept any expressions
    Codeforces Round #273 (Div. 2)-A. Initial Bet
    队列

    Codeforces Round #272 (Div. 2)-C. Dreamoon and Sums
  • 原文地址:https://www.cnblogs.com/end/p/981941.html
Copyright © 2020-2023  润新知