如何存放在我的web.config文件Dictionary对象? [英] How do I store a dictionary object in my web.config file?

查看:318
本文介绍了如何存放在我的web.config文件Dictionary对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想存储简单的键/值的字符串字典,我的网络配置文件。 Visual Studio中可以很容易地存储一个字符串集合(见下面的示例),但我不知道如何与一个字典集合做到这一点。

 < ArrayOfString的xmlns:XSI =htt​​p://www.w3.org/2001/XMLSchema-instance的xmlns:XSD =htt​​p://www.w3.org / 2001 / XML模式>
          <字符串>值1< /串>
          <字符串>值2< /串>
          <字符串>值2< /串>
        < / ArrayOfString>
 

解决方案

为什么要推倒重来?该的AppSettings 部分被设计用于存储字典的数据在你的配置文件完全相同的目的。

如果你不想投入过多的数据在你的AppSettings部分中,您可以按以下组的相关值到他们自己的部分:

 <结构>
  < configSections>
    <节
      NAME =MyDictionary
      TYPE =System.Configuration.NameValueFileSectionHandler,系统,版本= 1.0.3300.0,文化=中性公钥= b77a5c561934e089/>
  < / configSections>

  < MyDictionary>
     <添加键=名称1值=值1/>
     <添加键=名2的价值=值2/>
     <添加键=NAME3值=值3/>
     <添加键=名称4的价值=值4/>
  < / MyDictionary>
< /结构>
 

您可以通过访问元素在此集合

 使用System.Collections.Specialized;
使用System.Configuration;

公共字符串GetName1()
{
    NameValueCollection中部分=
        (NameValueCollection中)ConfigurationManager.GetSection(MyDictionary);
    返回节[NAME1];
}
 

I'd like to store a simple key/value string dictionary in my web config file. Visual Studio makes it easy to store a string collection(see sample below) but I'm not sure how to do it with a dictionary collection.

        <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <string>value1</string>
          <string>value2</string>
          <string>value2</string>
        </ArrayOfString>

解决方案

Why reinvent the wheel? The AppSettings section is designed for exactly the purpose of storing dictionary-like data in your config file.

If you don't want to put too much data in your AppSettings section, you can group your related values into their own section as follows:

<configuration>
  <configSections>
    <section 
      name="MyDictionary" 
      type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>

  <MyDictionary>
     <add key="name1" value="value1" />
     <add key="name2" value="value2" />
     <add key="name3" value="value3" />
     <add key="name4" value="value4" />
  </MyDictionary>
</configuration>

You can access elements in this collection using

using System.Collections.Specialized;
using System.Configuration;

public string GetName1()
{
    NameValueCollection section =
        (NameValueCollection)ConfigurationManager.GetSection("MyDictionary");
    return section["name1"];
}

这篇关于如何存放在我的web.config文件Dictionary对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆