App.config无法找到我的元素

时间:2015-02-03 18:49:31

标签: c# app-config

我有一个简单的app.config文件,它不能完全通过IDE检查程序。

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="XmlRoot" type="System.String"/>
  </configSections>
  <connectionStrings>
    <omitted/>
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>
  <XmlRoot>
    <add key="relativepath" value=""/>
  </XmlRoot>
</configuration>

我将<section name="XmlRoot" type="System.String" />部分添加到配置中,然后我尝试在此处定义名称和密钥:<add key="relativepath" value=""/>。但由于某种原因,IDE给了我以下消息:

enter image description here

我很少使用app.config文件,因此它可能只是一个noob错误。如何让它识别我的标签?

3 个答案:

答案 0 :(得分:2)

如果它只是一个简单的字符串,您可以使用AppSettings来完成此操作。

<configuration>
  <appSettings>
    <add key="relativepath" value="mypath" />
  </appSettings>
</configuration>

从C#访问它,如下所示:

string path = ConfigurationManager.AppSettings["relativepath"]);

答案 1 :(得分:0)

尝试将您的类型更改为System.Configuration.NameValueSectionHandler

这是我定义我的部分的方式:

<configSections>
<sectionGroup name="MySettings">
  <section name="serverConfiguration" type="System.Configuration.NameValueSectionHandler"></section>
  <section name="sqlSettings" type="System.Configuration.NameValueSectionHandler"></section>
</sectionGroup>    
 </configSections>

...

<MySettings>
<sqlSettings>
  <add key="sqlTransactionTimeOut" value="0" />
</sqlSettings>
<serverConfiguration>      
  <add key="resolveDnsAsync" value="true" />
</serverConfiguration>
</MySettings>

答案 2 :(得分:-1)

您可能需要使用appSettings

部分
<configuration>
     <appSettings> 
         <!-- and Here you define the key and the value like you do-->
         <add key="relativepath" value="path"/>
    </appSettings>
</configuration>

然后在你的代码中写下这样的内容来阅读它。

String path = ConfigurationManager.AppSettings["relativepath"].ToString();

希望它适合你。

:)

相关问题