C# 在.Net Core中使用app.config
我有问题。我需要在.Net Core(C#)中编写一个程序,它使用app.config,如下所示:C# 在.Net Core中使用app.config,c#,.net-core,C#,.net Core,我有问题。我需要在.Net Core(C#)中编写一个程序,它使用app.config,如下所示: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="custom" type="ConfigurationSample.CustomConfigurationSection, ConfigurationSample"/&g
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="custom" type="ConfigurationSample.CustomConfigurationSection, ConfigurationSample"/>
</configSections>
<connectionStrings>
<add name="sampleDatabase" connectionString="Data Source=localhost\SQLExpress;Initial Catalog=SampleDatabase;Integrated Security=True"/>
</connectionStrings>
<appSettings>
<add key="sampleApplication" value="Configuration Sample"/>
</appSettings>
<custom>
<customConfigurations>
<add key="customSample" name="Mickey Mouse" age="83"/>
</customConfigurations>
</custom>
</configuration>
这是来自互联网的一个例子,所以我认为这是可行的,但我得到了例外:
System.Configuration.ConfigurationErrorsException: 'Error Initializing the configuration system.'
Inner Exception
TypeLoadException: Could not load type 'System.Configuration.InternalConfigurationHost' from assembly 'CoreCompat.System.Configuration, Version=4.2.3.0, Culture=neutral, PublicKeyToken=null' because the method 'get_bundled_machine_config' has no implementation (no RVA).
我通过NuGet下载了安装包CoreCompat.System.Configuration-Version 4.2.3-r4-Pre,但仍然不起作用。也许有人能帮我
.JSON
文件)是最合适的配置源
注意:当有人说配置文件应该是appsettings.json
时,不要感到困惑。您可以使用任何适合您的文件名,并且文件位置可能不同-没有特定的规则
但是,由于现实世界很复杂,有很多不同的配置提供程序:
- 文件格式(INI、JSON和XML)
- 命令行参数
- 环境变量
app.config
配置文件是一个XML文件。因此,您可以使用XML配置提供程序(,)从中读取设置。但请记住,它将仅用作配置源-应用程序行为的任何逻辑都应由您实现。配置提供程序不会更改应用程序的“设置”和设置策略,只会从文件中读取数据即使在Linux上的.NET Core 2.0中,也可以使用通常的
System.Configuration
。尝试以下测试示例:
MyLib.dll
)System.Configuration.ConfigurationManager
v4.4.0。这是必需的,因为元包NetStandard.Library
v2.0.0不包含此包(我希望更改)ConfigurationSection
或ConfigurationElement
派生的所有C#类进入MyLib.dll
。例如MyClass.cs
源自ConfigurationSection
和MyAccount.cs
源自ConfigurationElement
。这里的实现细节不在范围之内,但是MyApp.dll
)。NET核心应用程序以.dll
结尾,而不是框架中的.exe
MyApp
中创建app.config
。这显然应该与上面#3中的类设计相匹配。例如:
就是这样-您会发现app.config在MyApp
中被正确解析,而MyLib
中的现有代码工作正常。如果您将平台从Windows(dev)切换到Linux(test),请不要忘记运行dotnet restore
测试项目的其他解决方案
如果您发现您的App.config
在您的测试项目中不起作用,您可能需要在测试项目的.csproj
中使用此代码段(例如,就在结束
之前)。它基本上是将App.config
作为testhost.dll.config
复制到您的输出文件夹中,因此dotnet test
会将其拾取
我有一个.Net Core 3.1 MSTest项目,有类似的问题。这篇文章提供了修复它的线索 将此分解为.Net core 3.1的简单答案:
- 向项目添加/确保nuget包:System.Configuration.ConfigurationManager
- 将app.config(xml)添加到项目中
- 将项目中的文件重命名为testhost.dll.config 或
- 使用由DeepSpace101提供的生成后命令
System.Configuration.ConfigurationErrorsException: 'Error Initializing the configuration system.'
Inner Exception
TypeLoadException: Could not load type 'System.Configuration.InternalConfigurationHost' from assembly 'CoreCompat.System.Configuration, Version=4.2.3.0, Culture=neutral, PublicKeyToken=null' because the method 'get_bundled_machine_config' has no implementation (no RVA).