C# 从类库项目中的 App.config 读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9871948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read from App.config in a Class Library project
提问by Yasser Shaikh
I am developing a simple class libraryproject, which will give me a dll.
我正在开发一个简单的类库项目,它会给我一个 dll。
I wanted a particular value to be read from a config file. So I have added an App.config file to my project.
我想从配置文件中读取一个特定的值。所以我在我的项目中添加了一个 App.config 文件。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="serviceUrl" value="test value" />
</appSettings>
</configuration>
Above is my App.config file, and now I am trying to read it as following
以上是我的 App.config 文件,现在我正在尝试按以下方式阅读它
string strVal = System.Configuration.ConfigurationManager.AppSettings["serviceUrl"];
But I am not getting any value in my string variable.
但是我的字符串变量没有得到任何值。


I had done this for a web application in a similar way and it worked. But somehow I am not able to get this working.
我以类似的方式为 Web 应用程序完成了此操作,并且它有效。但不知何故,我无法让这个工作。
Is the idea of having App.config in a class library project correct in the first place ?
首先在类库项目中使用 App.config 的想法是否正确?
采纳答案by Darren
As stated in my comment, add the App.Config file to the main solution and not in the class library project.
如我的评论中所述,将 App.Config 文件添加到主解决方案而不是类库项目中。
回答by Vijay Channe
You dont need to add app.config file. If you create class library for web based application then you can fetch connection string directly from web.config file
您不需要添加 app.config 文件。如果您为基于 Web 的应用程序创建类库,那么您可以直接从 web.config 文件中获取连接字符串
OR
或者
You can add any text file with connection string in it and fetch that string . using this
您可以添加任何带有连接字符串的文本文件并获取该字符串。使用这个
public static ConnectionStringSettings ConnSettings
{
get
{
string connectionStringKey = null;
connectionStringKey = ConfigurationManager.AppSettings.Get("DefaultConnectionString");
return ConfigurationManager.ConnectionStrings[connectionStringKey];
}
}
回答by civilator
assuming the question is asking for a config file specific to the dll project, not the app or web app project's config file, I used the following code to get the values from keys in the "sqlSection" section. (one caution is that this config file - even when it is set to copy always- is not automatically copied on a partial build of a web app. so I used the awesome one-line pre-build action to copy the file over, as mentioned in this post https://stackoverflow.com/a/40158880/1935056).
假设问题是要求特定于 dll 项目的配置文件,而不是应用程序或 Web 应用程序项目的配置文件,我使用以下代码从“sqlSection”部分的键中获取值。(一个警告是这个配置文件 - 即使它被设置为始终复制 - 不会在 Web 应用程序的部分构建中自动复制。所以我使用了很棒的单行预构建操作来复制文件,如在这篇文章中提到https://stackoverflow.com/a/40158880/1935056)。
here is the entire dll config file
这是整个 dll 配置文件
<?xml version="1.0" encoding="utf-8" ?>
<sqlSection>
<add key="sql1" value="--statement--"/>
</sqlSection>
this is the c# code.
这是 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();
}
回答by The champ
My code to read the configuration file
我读取配置文件的代码
Int32 FilesCountLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FilesTotalCount"]);
long FilesLengthLimit = Convert.ToInt64(ConfigurationManager.AppSettings["FilesTotalSize"]);
example for my app.config file
我的 app.config 文件的示例
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="FilesTotalCount" value="1000" />
<add key="FilesTotalSize" value="500000000" />
</appSettings>
</configuration>
If your solution has multiple projects listed, make sure the app settings are in the start up project, else you will be getting null as answer.
如果您的解决方案列出了多个项目,请确保应用程序设置在启动项目中,否则您将得到 null 作为答案。
回答by DrCrazyApe
Access App.Config from Executeable in Class Library project.
从类库项目中的 Executeable 访问 App.Config。
Project 1: Sample (executeable project .exe)
项目 1:示例(可执行项目 .exe)
Project 2: Sample.Database (class library project .dll)
项目2:Sample.Database(类库项目.dll)
Project 1 contains the app.config:
项目 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>
Project 2 needs access to the Configuration Settings... Create following classes:
项目 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;
}
}
Static Class in dll Project:
dll项目中的静态类:
public static class DBConnection
{
public static string ConnectionStringLocal => AssemblyConfiguration.GetConnectionString("Connection_Local");
}
Usage anywhere in class library project:
在类库项目中的任何地方使用:
var xx = DBConnection.ConnectionStringLocal;
If you don't want to read the Connection String on every function call, create a member variable in DBConnection and set it when it is null, otherwise return it.
如果不想在每次函数调用时都读取连接字符串,请在 DBConnection 中创建一个成员变量,并在它为 null 时设置它,否则返回它。

