如何在我的web.config文件中存储一个字典对象? [英] How do I store a dictionary object in my web.config file?

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

问题描述

我想在我的Web配置文件中存储一个简单的键/值字符串字典。 Visual Studio可以方便地存储字符串集合(请参见下面的示例),但我不知道如何使用字典集合。

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


解决方案

为什么要重新发明轮? AppSettings 部分专门用于在配置文件中存储类似字典的数据



如果您不想在您的AppSettings部分放置太多数据,您可以将相关值分组到自己的部分,如下所示:

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

< MyDictionary>
< add key =name1value =value1/>
< add key =name2value =value2/>
< add key =name3value =value3/>
< add key =name4value =value4/>
< / MyDictionary>
< / configuration>

您可以使用



访问此集合中的元素pre> 使用System.Collections.Specialized;
使用System.Configuration;

public string GetName1()
{
NameValueCollection section =
(NameValueCollection)ConfigurationManager.GetSection(MyDictionary);
return section [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文件中存储一个字典对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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