如何读取 Net5 中的配置文件?

How can read config file in Net5?

我使用 Vb.net , FW: Net5

这是我的 app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
    <add key="ConnectString" value="DB/Sample.db3" />
  </appSettings>
    <system.diagnostics>
        <sources>
            <!-- This section defines the logging configuration for My.Application.Log -->
            <source name="DefaultSource" switchName="DefaultSwitch">
                <listeners>
                    <add name="FileLog"/>
                    <!-- Uncomment the below section to write to the Application Event Log -->
                    <!--<add name="EventLog"/>-->
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="DefaultSwitch" value="Information" />
        </switches>
        <sharedListeners>
            <add name="FileLog"
                 type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" 
                 initializeData="FileLogWriter"/>
            <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
            <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
        </sharedListeners>
    </system.diagnostics>
</configuration>

我从 Nuget

安装 "System.Configuration.ConfigurationManager"

我曾尝试获取配置为:

Dim str = System.Configuration.ConfigurationManager.AppSettings("ConnectString")

但出现异常错误:

Configuration system failed to initialize

如何在 VB Net5 中读取 app.config?

我尝试在 .NET 5.0 应用程序中使用 app.config 文件,但我遇到了同样的异常。和你不一样,我看得更远一点,看到它也说它遇到了一个未知的部分,即system.diagnostics。然后我在我的配置文件中注释掉 <system.diagnostics> 元素并且它按预期工作。我不确定如果您确实需要使用该部分,您会怎么做,但看起来您并不需要,所以将其注释掉或删除应该不是问题。