如何存放在我的web.config文件Dictionary对象?在我、对象、文件、config

2023-09-02 20:43:47 作者:少年,伱已不再年少

我想存储简单的键/值的字符串字典,我的网络配置文件。 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>
< /结构>
 
这个Web.config文件上传了不能访问,应该怎么配置

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

 使用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"];
}