最近几天我试图在 c# 的应用程序控制台中创建用户机密,但我无法生成文件 secret 。
我最终遵循了 这个教程,终于能够创建 secret.xml 。但是当我试图从 secret.xml 文件中读取数据时,它给了我这个错误:
Thrown exception: 'System.Configuration.ConfigurationErrorsException' in System.Configuration.dll
An unhandled exception of type 'System.Configuration.ConfigurationErrorsException' occurred in System.Configuration.dll
An error occurred while loading a configuration file: Unable to load the file or assembly 'Microsoft.Configuration.ConfigurationBuilders.UserSecrets, Version = 1.0.0.0, Culture = neutral' or one of its dependencies. The specified file can not be found.
一开始我能够从配置文件中读取密码数据,但是当我尝试从秘密文件中读取密码数据时,它似乎不起作用。
尝试的解决方案: -删除对 UserSecrets 的引用,然后使用 Nuget 再次添加它。
这是我的代码:点击这里
应用程序配置:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false"/>
</configSections>
<configBuilders>
<builders>
<add name="Secrets" userSecretsFile="c:\\secrets\\secret.xml" type="Microsoft.Configuration.ConfigurationBuilders.UserSecretsConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.UserSecrets, Version=1.0.0.0, Culture=neutral"/>
</builders>
</configBuilders>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
<appSettings configBuilders="Secrets">
<add key="password" value="This is a password placeholder"/>
</appSettings>
</configuration>
程序.cs:
static void Main(string[] args)
{
var password = ConfigurationManager.AppSettings["password"];
Console.WriteLine($"Password is {password}");
}