Using config file in .NET Standard does not work

|▌冷眼眸甩不掉的悲伤 提交于 2020-06-12 05:10:36

问题


How can you use a console config file (App.config) in a .NET Standard project.

I have one console application with in the App.config:

<appSettings>
    <add key="Test" value="test" />
</appSettings>

In my .NET Standard project I added the NuGet package:

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0 

And have a class that returns the value of that Key:

public string Test()
        {  
            return ConfigurationManager.AppSettings["Test"];
        }

This is just to test if I could use App.config settings in a .NET Standard project.

But I get this error message:

System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.'

When I do this in Program.cs:

Class class = new Class();
string result = class.Test();

回答1:


I was able to reproduce the behavior you mentioned, and to fix it I referenced the System.Configuration.ConfigurationManager -Version 4.5.0 on the Console project that consumes the test class.

The error is basically telling you that it cannot find that assembly in the output path, you referenced it in your .net standard project but it also needs to be referenced in the Console App that is launching the project.

That being said, also make sure that your config file <appSettings> section is under the <configuration> section such as this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
    <appSettings>
        <add key="Test" value="test" />
    </appSettings>
</configuration>

Hope this helps!



来源:https://stackoverflow.com/questions/52223906/using-config-file-in-net-standard-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!