Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using config file in .NET Standard does not work

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();
like image 945
user7849697 Avatar asked Sep 07 '18 13:09

user7849697


People also ask

How do I access config in C#?

New Project > Visual C# > Console Application Configuration assembly reference to access configuration settings, using ConfigurationManager. To add the reference, just right click References and click to add references. Now, we can see that System. Configuration reference has been added successfully to our project.

Does .NET core use app config?

Application configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources: Settings files, such as appsettings. json.

What is a config file in C#?

App. Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.


1 Answers

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!

like image 105
Leo Hinojosa Avatar answered Sep 22 '22 18:09

Leo Hinojosa