c# - .exe 和 .dll 之间的共享配置

标签 c# app-config configuration-files

我正在尝试在我的项目中使用 settings.settings 文件。有些值需要在 .exe 文件和各种 DLL 之间共享。我不想只是传递这些值,我想在需要时访问它们,但每个项目设置其值的名称略有不同,因此其他项目无法访问它们。

有没有办法使用 settings.settings 方法在 .exe 和 .dll 之间共享 app.config 文件的内容?还是我需要返回使用 ConfigurationManager 才能执行此操作?

最佳答案

只需将您的设置放在 App.config 文件中,然后从您的 dll 中读取它们。事实上,我相信这是你的 dll 唯一会寻找设置/配置的地方,dll 的本地配置将被忽略。

这里有一个简单的例子来确保 dll 没有对应用程序的强引用。这段代码不是很好,但你明白了。

  private string GetSettingValue(string key)
  {
     string executingAssembly = Assembly.GetEntryAssembly().GetName().Name;
     string sectionName = "applicationSettings/" + executingAssembly 
                                                 + ".Properties.Settings";
     ClientSettingsSection section =
            (ClientSettingsSection)ConfigurationManager.GetSection(sectionName);

     // add null checking etc
     SettingElement setting = section.Settings.Get(key); 
     return setting.Value.ValueXml.InnerText;
  }

或者有一个带有共享设置的公共(public) dll,并从需要共享配置的每个程序集中获取依赖项。这要干净得多。

关于c# - .exe 和 .dll 之间的共享配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7336215/

相关文章:

c# - .NET 程序集内存使用

c# - CS0034 C# 运算符 '-' 在类型为 'long' 和 'ulong' 的操作数上不明确

.net - web.config 是否覆盖任何 app.configs?

c# - 如何从应用程序级别使用 Azure 中的服务配置?

javascript - 将配置文件添加到我的 JavaScript 项目

c# - 访问 JSON 字符串中的无效成员名称

c# - Entity Framework 4 获取插入记录的主键 ID

.net - 有没有方法可以覆盖ConfigurationManager.AppSettings?

Symfony2 JMSSerializerBundle 在 YML 中公开属性

python - 使用配置文件打包 Python 应用程序