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

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

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

我读到我应该使用:

ConfigurationManager.AppSettings["MySetting"]

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

最好的方法是什么?


当前回答

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

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
}

其他回答

我在这个链接https://stackoverflow.com/a/1836938/1492229找到了答案

不仅需要使用名称空间System.Configuration。您还必须将引用添加到程序集System.Configuration.dll,通过

右键单击引用/依赖项 选择添加参考 找到并添加System.Configuration。

这肯定有用。 同样,对于NameValueCollection,你必须写:

using System.Collections.Specialized;

对于如下所示的示例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"];

额外:如果你正在处理一个类库项目,你必须嵌入设置。json文件。

类库不应该直接引用 App.config类没有App.config,因为它不是一个 Application是一个类。

转到JSON文件的属性。 Change Build Action ->嵌入式资源。 使用下面的代码来阅读它。

var assembly = assembly . getexecutingassembly ();

var resourceStream = assembly。GetManifestResourceStream(“Assembly.file.json”);

string myString = reader.ReadToEnd();

现在我们有一个JSON字符串,我们可以使用JsonConvert反序列化它

如果您没有在程序集中嵌入该文件,则不能只使用DLL文件而不使用该文件

我正在用这个,对我来说效果很好:

textBox1.Text = ConfigurationManager.AppSettings["Name"];

此外,您可以使用Formo:

配置:

<appSettings>
    <add key="RetryAttempts" value="5" />
    <add key="ApplicationBuildDate" value="11/4/1999 6:23 AM" />
</appSettings>

代码:

dynamic config = new Configuration();
var retryAttempts1 = config.RetryAttempts;                 // Returns 5 as a string
var retryAttempts2 = config.RetryAttempts(10);             // Returns 5 if found in config, else 10
var retryAttempts3 = config.RetryAttempts(userInput, 10);  // Returns 5 if it exists in config, else userInput if not null, else 10
var appBuildDate = config.ApplicationBuildDate<DateTime>();