【问题标题】:Read from App.config in a Class Library project从类库项目中的 App.config 中读取
【发布时间】:2012-04-09 22:42:23
【问题描述】:

我正在开发一个简单的类库项目,它会给我一个 dll。

我想从配置文件中读取一个特定的值。所以我在我的项目中添加了一个 App.config 文件。

 <?xml version="1.0" encoding="utf-8" ?>
 <configuration>

  <appSettings>
  <add key="serviceUrl" value="test value" />
  </appSettings>

  </configuration>

上面是我的 App.config 文件,现在我尝试如下读取它

  string strVal = System.Configuration.ConfigurationManager.AppSettings["serviceUrl"];

但我的字符串变量中没有任何值。

我以类似的方式为 Web 应用程序完成了此操作,并且成功了。 但不知何故,我无法让这个工作。

首先在类库项目中包含 App.config 的想法是否正确?

【问题讨论】:

  • 您有多个 App.config 文件吗?尝试调试并查看 ConfigurationManager.AppSettings 中的密钥计数,如果显示为 0,我会假设 VS 未检测到您的应用配置文件。
  • 我只有一个 app.config,并且附上了我的调试屏幕截图
  • 将应用配置文件添加到主项目中,而不是在类库程序集中。
  • 要检查这个我正在做的是...我创建了一个测试项目,我正在调用在这个类库中创建的一个类中定义的公共方法之一。这个类库项目有一个 app.config。
  • 我的解决方案中有两个项目 1. 类库 2. 测试项目在哪里添加?

标签: c# .net app-config class-library


【解决方案1】:

如我评论中所述,将 App.Config 文件添加到主解决方案而不是类库项目中。

【讨论】:

  • 我的解决方案中有两个项目 1. 类库 2. 测试项目我在哪里添加它?
  • 找到了!感谢 Darren,我尝试将 app.config 添加到我的测试项目中,当我输入 ConfigurationManager.AppSetting ...类项目我回去删除了 4.0 引用并添加了 2.0 一个,现在它可以工作了!!
【解决方案2】:

您不需要添加 app.config 文件。 如果您为基于 Web 的应用程序创建类库,那么您可以获取连接 直接来自 web.config 文件的字符串

您可以添加任何带有连接字符串的文本文件并获取该字符串。 使用这个

public static ConnectionStringSettings ConnSettings
{
    get
    {
        string connectionStringKey = null;
        connectionStringKey = ConfigurationManager.AppSettings.Get("DefaultConnectionString");
        return ConfigurationManager.ConnectionStrings[connectionStringKey];          
    }
}

【讨论】:

    【解决方案3】:

    假设问题是要求特定于 dll 项目的配置文件,而不是应用程序或 Web 应用程序项目的配置文件,我使用以下代码从“sqlSection”部分中的键获取值。 (需要注意的是,这个配置文件——即使它被设置为始终复制——也不会自动复制到 web 应用程序的部分构建中。所以我使用了令人敬畏的单行预构建操作来复制文件,因为在这篇文章中提到了https://stackoverflow.com/a/40158880/1935056)。

    这里是整个 dll 配置文件

    <?xml version="1.0" encoding="utf-8" ?>
    
    
    <sqlSection>
    
    <add key="sql1" value="--statement--"/>
    </sqlSection>
    

    这是 C# 代码。

     string GetSqlStatement(string key)
        {
                string path =   Path.GetDirectoryName(Assembly.GetCallingAssembly().CodeBase) + @"\DataLayer.dll.config";
    
            XDocument doc = XDocument.Load(path);
    
            var query = doc.Descendants("sqlSection").Nodes().Cast<XElement>().Where(x => x.Attribute("key").Value.ToString() == key).FirstOrDefault();
    
            if (query != null)
            {
                return query.Attribute("value").Value.ToString();
            }
    

    【讨论】:

      【解决方案4】:

      我的代码读取配置文件

      Int32 FilesCountLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FilesTotalCount"]);
          long FilesLengthLimit = Convert.ToInt64(ConfigurationManager.AppSettings["FilesTotalSize"]);
      

      我的 app.config 文件示例

      <?xml version="1.0" encoding="utf-8"?>
      <configuration>
        <appSettings>
          <add key="FilesTotalCount" value="1000" />
          <add key="FilesTotalSize" value="500000000" />
        </appSettings>
      </configuration>
      

      如果您的解决方案列出了多个项目,请确保应用设置在启动项目中,否则您将得到 null 作为答案。

      【讨论】:

        【解决方案5】:

        从类库项目中的可执行文件访问 App.Config。

        项目1:示例(可执行项目.exe)

        项目2:Sample.Database(类库项目.dll)

        项目 1 包含 app.config:

        <?xml version="1.0" encoding="utf-8"?>
        <configuration>
          <startup>
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
          </startup>
          <connectionStrings>
            <clear />
            <add name="Connection_Local" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\work\WF\ScaleCalibration\ScaleCalibration\AppData\db_local.mdf;Integrated Security=True;Connect Timeout=30" />
          </connectionStrings>>
        </configuration>
        

        项目 2 需要访问配置设置...创建以下类:

        public class AssemblyConfiguration : MarshalByRefObject
        {
            public static string GetConnectionString(string name)
            {
                Assembly callingAssembly = Assembly.GetEntryAssembly();
                var conStringCollection = ConfigurationManager.OpenExeConfiguration(callingAssembly.Location).ConnectionStrings;
                return conStringCollection?.ConnectionStrings[name].ConnectionString;
            }
        }
        

        dll 项目中的静态类:

        public static class DBConnection
        {
            public static string ConnectionStringLocal => AssemblyConfiguration.GetConnectionString("Connection_Local");
        }
        

        在类库项目中的任何地方使用:

        var xx = DBConnection.ConnectionStringLocal;
        

        如果不想每次函数调用都读取Connection String,可以在DBConnection中创建一个成员变量,为null时设置,否则返回。

        【讨论】:

          【解决方案6】:

          已解决

          我遇到过这个问题。我所做的如下。

          这就是代码的样子

          1. App.config

          1. 来自类库

          【讨论】:

            猜你喜欢
            • 2013-07-06
            • 2023-03-03
            • 2011-07-30
            • 1970-01-01
            • 2012-10-14
            • 2020-03-20
            • 2018-07-30
            • 2015-12-27
            • 2012-03-20
            相关资源
            最近更新 更多