[英]How to use ConfigurationManager.AppSettings with a custom section?
我需要從使用 App.config 文件中獲取“ http://example.com ”。
但目前我正在使用:
string peopleXMLPath = ConfigurationManager.AppSettings["server"];
我無法獲得價值。
你能指出我做錯了什么嗎?
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="device" type="System.Configuration.SingleTagSectionHandler" />
<section name="server" type="System.Configuration.SingleTagSectionHandler" />
</configSections>
<device id="1" description="petras room" location="" mall="" />
<server url="http://example.com" />
</configuration>
我認為您需要獲取配置部分,並訪問它:
var section = ConfigurationManager.GetSection("server") as NameValueCollection;
var value = section["url"];
你還需要更新你的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="device" type="System.Configuration.NameValueSectionHandler" />
<section name="server" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<device>
<add key="id" value="1" />
<add key="description" value="petras room" />
<add key="location" value="" />
<add key="mall" value="" />
</device>
<server>
<add key="url" value="http://example.com" />
</server>
</configuration>
編輯:正如 CodeCaster 在他的回答中提到的, SingleTagSectionHandler
僅供內部使用。 我認為NameValueSectionHandler
是定義配置部分的首選方式。
此 API 支持 .NET Framework 基礎結構,不應直接從您的代碼中使用。
您可以將其作為HashTable
檢索並使用Configuration.GetSection()
訪問其條目:
Hashtable serverTag = (Hashtable)ConfigurationManager.GetSection("server");
string serverUrl = (string)serverTag["url"];
string peopleXMLPath = ConfigurationManager.AppSettings["server"];
從 app.config 文件的appSettings
部分獲取值,但您將值存儲在
<server url="http://example.com" />
將值放入appSettings
部分,如下所示,或者從其當前位置檢索值。
您需要向配置的 appSettings 部分添加一個鍵值對。 如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="server" value="http://example.com" />
</appSettings>
</configuration>
您的閱讀代碼是正確的,但您可能應該檢查是否為空。 如果代碼無法讀取配置值,則string
變量將為空。
您正在定義配置部分而不是AppSettings
中的值。 您可以簡單地將您的設置添加到AppSettings
:
<appSettings>
... may be some settings here already
<add key="server" value="http://example.com" />
</appSettings>
自定義配置部分通常用於更復雜的配置(例如每個鍵多個值、非字符串值等。
如果要從應用設置中獲取值,配置文件中的 appsetting 元素必須有一個鍵。
在配置部分下定義您的服務器值,如下所述:
<configuration>
<appSettings>
<add key="server" value="http://example.com" />
</appSettings>
...
...
...
</configuration>
現在執行以下代碼行以獲取服務器 url:
string peopleXMLPath = ConfigurationManager.AppSettings["server"].ToString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.