如何使用ConfigurationManager

gbk*_*gbk 38 .net c# configuration config winforms

我想使用App.config存储一些设置.我尝试使用下一个代码从配置文件中获取参数.

private string GetSettingValue(string paramName)
{
    return String.Format(ConfigurationManager.AppSettings[paramName]);
}
Run Code Online (Sandbox Code Playgroud)

我也System.Configuration为它添加了(我使用了一个单独的类),在App.config文件中我有:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <appSettings>
    <add key ="key1" value ="Sample" />
  </appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

但是我在尝试使用时遇到了错误ConfigurationManager- ConfigurationManager can't exist in such context但是我已经添加了System.Configuration.还是我错过了什么?

编辑:

带配置的类(完整视图)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace browser
{
    class ConfigFile
    {
        private string GetSettingValue(string paramName)
        {
            return String.Format(ConfigurationManager.AppSettings[paramName]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

EDIT2

添加它的外观

在此输入图像描述

这意味着问题不是在使用过程中,ConfigurationManger而是在使用之前 - 程序"说"它"不知道这样的元素",因为我理解错误 - "Element ConfigurationManager"在这样的上下文中不存在"

EDIT3

在此输入图像描述

编辑4

在此输入图像描述

Mik*_*oud 30

好吧,我花了一段时间才看到这个,但是没有办法编译:

return String.(ConfigurationManager.AppSettings[paramName]);
Run Code Online (Sandbox Code Playgroud)

你甚至没有在String类型上调用方法.这样做:

return ConfigurationManager.AppSettings[paramName];
Run Code Online (Sandbox Code Playgroud)

AppSettingsKeyValuePair已经返回一个字符串.如果名称不存在,则返回null.


根据您的编辑,您还没有为您正在使用的项目添加System.Configuration程序集的引用.


小智 7

转到tools>> nuget>>console并键入:

Install-Package System.Configuration.ConfigurationManager 
Run Code Online (Sandbox Code Playgroud)

如果你想要一个特定的版本:

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0
Run Code Online (Sandbox Code Playgroud)

您的ConfigurationManager dll现在将被导入,代码将开始工作。