我正在编写一个c#类库,需要能够从web读取设置。config或app.config文件(取决于DLL是否从ASP. config引用。NET web应用程序或Windows窗体应用程序)。

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

但该代码已被微软标记为弃用。

我读到我应该使用:

ConfigurationManager.AppSettings["MySetting"]

但是,在c#类库项目中,System.Configuration.ConfigurationManager类似乎不可用。

最好的方法是什么?


当前回答

必须向系统添加引用。项目的配置程序集。

其他回答

我强烈建议您为这个调用创建一个包装器。类似于ConfigurationReaderService,并使用依赖注入来获取这个类。通过这种方式,您将能够为测试目的隔离这些配置文件。

所以使用ConfigurationManager.AppSettings["something"];建议并返回该值。如果.config文件中没有任何可用的键,您可以使用此方法创建某种默认返回。

必须向系统添加引用。项目的配置程序集。

您需要向System添加一个引用。在项目的引用文件夹中的配置。

你绝对应该使用ConfigurationManager,而不是过时的ConfigurationSettings。

我发现最好的方法,以系统的方式访问应用程序设置变量,通过在系统上制作包装类。配置如下

public class BaseConfiguration
{
    protected static object GetAppSetting(Type expectedType, string key)
    {
        string value = ConfigurationManager.AppSettings.Get(key);
        try
        {
            if (expectedType == typeof(int))
                return int.Parse(value);
            if (expectedType == typeof(string))
                return value;

            throw new Exception("Type not supported.");
        }
        catch (Exception ex)
        {
            throw new Exception(string.Format("Config key:{0} was expected to be of type {1} but was not.",
                key, expectedType), ex);
        }
    }
}

现在我们可以通过硬编码的名称使用另一个类访问所需的设置变量,如下所示:

public class ConfigurationSettings:BaseConfiguration
{
    #region App setting

    public static string ApplicationName
    {
        get { return (string)GetAppSetting(typeof(string), "ApplicationName"); }
    }

    public static string MailBccAddress
    {
        get { return (string)GetAppSetting(typeof(string), "MailBccAddress"); }
    }

    public static string DefaultConnection
    {
        get { return (string)GetAppSetting(typeof(string), "DefaultConnection"); }
    }

    #endregion App setting

    #region global setting


    #endregion global setting
}

请检查您正在使用的. net版本。它应该大于4。你必须添加系统。配置系统库到您的应用程序。