将没有app.config文件的硬编码配置添加到某个程序集

本文关键字:添加 配置 程序集 编码 app config 文件 | 更新日期: 2023-09-27 18:11:29

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

编辑:

我需要这样的东西

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

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

将没有app.config文件的硬编码配置添加到某个程序集

如果用户或应用程序设置在默认情况下将其默认值"硬编码"在程序集中,则配置设置。可以通过包含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");
// ...

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

见这里:我如何检索嵌入的xml资源?有关如何在运行时读取它的示例

编辑:并将其加载为自定义配置文件,请查看这里:加载自定义配置文件