如何使用ConfigurationManager中 [英] How to use ConfigurationManager

查看:153
本文介绍了如何使用ConfigurationManager中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use App.config for storing some setting. I tried to use the next code for getting a parameter from a config file.

private string GetSettingValue(string paramName)
{
    return String.Format(ConfigurationManager.AppSettings[paramName]);
}



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

I also added System.Configuration for it (I used a separate class), and in App.config file I have:

<?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>



不过,虽然尝试使用我得到了一个错误 ConfigurationManager中 - ConfigurationManager中不能在这样的背景下存在,但我已经添加了 System.Configuration 。还是我错过了什么。

But I got an error while trying to use ConfigurationManager - ConfigurationManager can't exist in such context, but I already added System.Configuration. Or did I miss something?

修改

类配置(全视图)

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



EDIT2

添加它的外观

这意味着问题不使用时 ConfigurationManger 但在此之前 - 节目说,它不知道这样的元素,我理解错误 - 元素ConfigurationManager中并不在这样的背景下存在

This means the problem is not during using ConfigurationManger but before - the program "says" that it "doesn't know such element" as I understand the error - the "Element ConfigurationManager" doesn't exist in such context"

EDIT3

修改4

推荐答案

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

Okay, it took me a while to see this, but there's not way this compiles:

return String.(ConfigurationManager.AppSettings[paramName]);

您甚至没有呼吁字符串类型。只要做到这一点:

You're not even calling a method on the String type. Just do this:

return ConfigurationManager.AppSettings[paramName];



的AppSettings KVP已经返回一个字符串。如果名称不存在,它将返回

The AppSettings KVP already returns a string. If the name doesn't exist, it will return null.

根据您的编辑,你还没有的添加了一个参考 System.Configuration 组装你的工作项目。

Based on your edit you have not yet added a Reference to the System.Configuration assembly for the project you're working in.

这篇关于如何使用ConfigurationManager中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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