我有问题。我需要在 .Net Core(C#) 中编写一个使用 app.config 的程序,如下所示:
<?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>
我写道:
string connectionString = ConfigurationManager.ConnectionStrings["sampleDatabase"].ConnectionString;
Console.WriteLine(connectionString);
// read appSettings configuration
string appSettingValue = ConfigurationManager.AppSettings["sampleApplication"];
Console.WriteLine(appSettingValue);
这是来自互联网的例子,所以我认为会起作用,但我得到了异常(exception):
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 - Install-Package CoreCompat.System.Configuration -Version 4.2.3-r4 -Pre 下载,但仍然无法正常工作。也许有人可以帮助我?
最佳答案
可以使用您平常使用的 System.Configuration
即使在 Linux 上的 .NET Core 2.0 中。试试这个测试示例:
MyLib.dll
)System.Configuration.ConfigurationManager
v4.4.0。这是必需的,因为这个包不在元包中 NetStandard.Library
v2.0.0(希望有所改变)ConfigurationSection
派生的所有 C# 类或 ConfigurationElement
进入MyLib.dll
.例如 MyClass.cs
源自 ConfigurationSection
和 MyAccount.cs
源自 ConfigurationElement
.实现细节超出了这里的范围,但 Google is your friend . MyApp.dll
)。 .NET Core 应用程序以 .dll
结尾而不是 .exe
在框架中。 app.config
在 MyApp
使用您的自定义配置部分。这显然应该与上面 #3 中的类设计相匹配。例如:<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
</configSections>
<myCustomConfig>
<myAccount id="007" />
</myCustomConfig>
</configuration>
就是这样 - 你会发现 app.config 在 MyApp
中被正确解析和您现有的代码 MyLib
工作得很好。不要忘记运行 dotnet restore
如果您将平台从 Windows(开发)切换到 Linux(测试)。测试项目的其他解决方法
如果您发现您的
App.config
在您的测试项目中不起作用,您可能需要在您的测试项目的 .csproj
中使用此代码段(例如,就在结尾 </Project>
之前)。它基本上是复制App.config
作为 testhost.dll.config
进入您的输出文件夹所以dotnet test
拿起它。 <!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
</Target>
<!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
关于c# - 在 .Net Core 中使用 app.config,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57108206/