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

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

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

我读到我应该使用:

ConfigurationManager.AppSettings["MySetting"]

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

最好的方法是什么?


当前回答

您可以将App.config文件添加到DLL文件中。config只适用于可执行的项目,因为所有DLL文件都从正在执行的EXE文件的配置文件中获取配置。

假设你的解决方案中有两个项目:

SomeDll SomeExe

您的问题可能与您将app.config文件包含到SomeDLL而不是SomeExe有关。SomeDll能够从SomeExe项目中读取配置。

其他回答

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

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
}

我总是为所有配置值创建一个带有类型安全属性的IConfig接口。然后,Config实现类将调用包装到System.Configuration。整个系统。配置调用现在在一个地方,维护和跟踪正在使用的字段并声明它们的默认值变得更加容易和清晰。我编写了一组私有帮助器方法来读取和解析常见数据类型。

使用IoC框架,你可以通过简单地将接口传递给类构造函数,在应用程序中的任何地方访问IConfig字段。你还可以在你的单元测试中创建IConfig接口的模拟实现,这样你就可以测试各种配置值和值组合,而不需要触及你的App.config或Web。配置文件。

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

我一直试图找到一个解决这个问题的几天了。我可以通过在web中的appsettings标签中添加一个键来解决这个问题。配置文件。这将在使用helper时覆盖.dll文件。

<configuration>
    <appSettings>
        <add key="loginUrl" value="~/RedirectValue.cshtml" />
        <add key="autoFormsAuthentication" value="false"/>
    </appSettings>
</configuration>

对于如下所示的示例app.config文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="countoffiles" value="7" />
    <add key="logfilelocation" value="abc.txt" />
  </appSettings>
</configuration>

使用下面所示的代码读取上述应用程序设置:

using System.Configuration;

您可能还需要添加对System的引用。在您的项目中配置(如果还没有的话)。然后你可以像这样访问这些值:

string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];