【问题标题】:Add hardcoded configuration without app.config file to some assembly将没有 app.config 文件的硬编码配置添加到某些程序集中
【发布时间】:2011-10-16 16:53:33
【问题描述】:

我需要将配置信息添加到程序集本身,而不包括它的 app.config 文件。 我该怎么做?

编辑: 我需要这样的东西

 string config = @"<?xml version='1.0' encoding='utf-8'?>
                   <configuration> 
                    .
                    .
                    .
                    .
                   </configuration>";

将此硬编码字符串配置设置为当前程序集配置

【问题讨论】:

  • 您想在程序集中嵌入配置吗?这就是所谓的常量:-)
  • 是的,这就是我想要的。
  • “程序集”标签用于低级编程,不适用于 .NET 程序集。

标签: c# .net configuration configuration-files


【解决方案1】:

默认情况下,无论是用户设置还是应用程序设置,它们的默认值都在程序集中“硬编码”。可以通过包含 app.config 或在运行时修改用户设置并保存到用户配置文件来覆盖它们。

创建项目设置后(在项目属性中并转到“设置”选项卡),将生成一个带有静态属性的 Settings 类,该类将具有您配置的默认值。

它们在整个程序集中都可以访问,如下所示:

Assert.AreEqual(Properties.Settings.MySetting, "MyDefaultValue");

这些默认值可以通过 app.config 覆盖:

<applicationSettings>
    <MyProject.Properties.Settings>
        <setting name="MySetting" serializeAs="String">
            <value>MyDefaultValue</value>
        </setting>
    </MyProject.Properties.Settings>
</applicationSettings>

回答您的问题:您可以在应用程序部署中省略包含 app.config,您在配置设置时提供的默认值是硬编码的。

编辑:

刚刚注意到您实际上想从您的程序集中读取 整个 app.config。 可能的方法如下:

// 1. Create a temporary file
string fileName = Path.GetTempFileName();
// 2. Write the contents of your app.config to that file
File.WriteAllText(fileName, Properties.Settings.Default.DefaultConfiguration);
// 3. Set the default configuration file for this application to that file
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", fileName);
// 4. Refresh the sections you wish to reload
ConfigurationManager.RefreshSection("AppSettings");
ConfigurationManager.RefreshSection("connectionStrings");
// ...

【讨论】:

  • 有没有办法一次刷新整个部分?!
  • 遗憾的是我没有找到。你可以使用 linq to xml 来遍历你的配置文件
【解决方案2】:

您可以有一个自定义 XML 文件来存储您的设置,然后将其设置为嵌入式资源,以便在 exe 或 dll 中可用。

请参阅此处:How can I retrieve an embedded xml resource?,了解如何在运行时读取它的示例

编辑:并将其加载为自定义配置文件,请在此处查看:Loading custom configuration files

【讨论】:

  • 如何设置为程序集的配置文件?
猜你喜欢
  • 1970-01-01
  • 2022-10-19
  • 1970-01-01
  • 2012-02-08
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
相关资源
最近更新 更多