在.NET Standard中使用配置文件不起作用 [英] Using config file in .NET Standard does not work

查看:415
本文介绍了在.NET Standard中使用配置文件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在.NET Standard项目中使用控制台配置文件(App.config).

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

我在App.config中有一个控制台应用程序:

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

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

在我的.NET Standard项目中,我添加了NuGet包:

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"];
        }

这只是为了测试我是否可以在.NET Standard项目中使用App.config设置.

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:'无法加载文件或程序集'System.Configuration.ConfigurationManager,版本= 4.0.1.0,区域性=中性,PublicKeyToken = cc7b13ffcd2ddd51'或其依赖项之一.系统找不到指定的文件.'

当我在Program.cs中执行此操作时:

When I do this in Program.cs:

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

推荐答案

我能够重现您提到的行为,并对其进行修复,因此我在使用测试类的Console项目上引用了System.Configuration.ConfigurationManager -Version 4.5.0.

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.

该错误基本上是在告诉您它无法在输出路径中找到该程序集,您在.net标准项目中对其进行了引用,但也需要在启动该项目的控制台应用程序中对其进行引用.

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.

话虽如此,还要确保您的配置文件<appSettings>部分位于<configuration>部分之下,例如:

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>

希望这会有所帮助!

这篇关于在.NET Standard中使用配置文件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆