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

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

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

我读到我应该使用:

ConfigurationManager.AppSettings["MySetting"]

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

最好的方法是什么?


当前回答

阅读配置:

你需要在配置中添加一个引用:

打开项目上的“属性” 进入“设置”选项卡 添加“名称”和“值” 使用以下代码获取价值: 字符串值= Properties.Settings.Default.keyname;

保存到配置:

   Properties.Settings.Default.keyName = value;
   Properties.Settings.Default.Save();

其他回答

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

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

另一个可能的解决方案:

var MyReader = new System.Configuration.AppSettingsReader();
string keyvalue = MyReader.GetValue("keyalue",typeof(string)).ToString();

你可以使用下面这条线。在我的例子中,它是有效的: System.Configuration.ConfigurationSettings.AppSettings(“yourKeyName”)

您必须注意上面的代码行也是旧版本,并且在新库中已弃用。

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

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
}

网络。配置用于web应用程序。网络。Config默认情况下有几个web应用程序所需的配置。你可以有一张网。为web应用程序下的每个文件夹配置。

app.config用于Windows应用程序。当您在Visual Studio中构建应用程序时,它将自动重命名为<appname>.exe。配置和此文件必须随应用程序一起交付。

你可以使用相同的方法从两个配置文件中调用应用程序设置值: System.Configuration.ConfigurationSettings.AppSettings(“关键”)