如何在web.config文件中存储字典对象?

TGn*_*nat 63 .net asp.net dictionary web-config

我想在我的Web配置文件中存储一个简单的键/值字符串字典.Visual Studio使得存储字符串集合变得容易(参见下面的示例),但我不确定如何使用字典集合来完成它.

        <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>
Run Code Online (Sandbox Code Playgroud)

Jul*_*iet 120

为什么重新发明轮子?该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="name1" value="value1" />
     <add key="name2" value="value2" />
     <add key="name3" value="value3" />
     <add key="name4" value="value4" />
  </MyDictionary>
</configuration>
Run Code Online (Sandbox Code Playgroud)

您可以使用访问此集合中的元素

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

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


Fac*_*tic 27

Juliet的答案很明确,但是你还可以在外部.config文件中添加其他配置,web.config方法如下:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <!-- blah blah the default stuff here -->

    <!-- here, add your custom section -->
    <section name="DocTabMap" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>

  <!-- your custom section, but referenced in another file -->
  <DocTabMap file="CustomDocTabs.config" />

  <!-- etc, remainder of default web.config is here -->
</configuration>
Run Code Online (Sandbox Code Playgroud)

然后,你CustomDocTabs.config看起来像这样:

<?xml version="1.0"?>
<DocTabMap>
  <add key="A" value="1" />
  <add key="B" value="2" />
  <add key="C" value="3" />
  <add key="D" value="4" />
</DocTabMap>
Run Code Online (Sandbox Code Playgroud)

现在您可以通过以下代码访问它:

NameValueCollection DocTabMap = ConfigurationManager.GetSection("DocTabMap") as NameValueCollection;
DocTabMap["A"] // == "B"
Run Code Online (Sandbox Code Playgroud)


Max*_*ler 5

您需要实现自定义部分(请参阅配置部分设计器).

你真正想要的是......接近这一点:

<MyDictionary>
  <add name="Something1" value="something else"/>
  <add name="Something2" value="something else"/>
  <add name="Something3" value="something else"/>
</MyDictionary>
Run Code Online (Sandbox Code Playgroud)

XmlAttribute"name"是一个Key,它不允许在后面的代码中有多个.同时,确保Collection MyDictionary也是一个Dictionary.

您可以使用此工具完成所有这些工作,并根据需要填补空白.