问题描述
我需要向程序集本身添加配置信息,而不要包含其app.config文件。
我该怎么办?
I need to add configuration information to the assembly itself without including its app.config file with it.How can i do it?
编辑:
我需要这样的东西
I need something like this
string config = @"<?xml version='1.0' encoding='utf-8'?>
<configuration>
.
.
.
.
</configuration>";
将此硬编码字符串配置设置为当前程序集配置
Set this hardcoded string configuration as current assembly configuration
推荐答案
默认情况下,配置设置是用户设置或应用程序设置的默认值都在程序集中硬编码。可以通过包含app.config或在运行时修改用户设置并将其保存到用户配置文件中来覆盖它们。
Configuration settings be it user or application settings have their default values "hardcoded" in the assembly by default. They can be overriden by including an app.config, or modifying user settings at runtime and saving to the user config file.
创建项目设置后(在项目属性中,然后转到设置选项卡),将创建一个 Settings
类
After creating project settings (in project properties and go to the "Settings" tab), a Settings
class is generated with static properties which will have the default value you configured.
它们可以在整个程序集中访问,如下所示:
They are accessible throughout your assembly like so:
Assert.AreEqual(Properties.Settings.MySetting, "MyDefaultValue");
这些默认值可以通过app.config覆盖:
These default values can be overridden via the app.config:
<applicationSettings>
<MyProject.Properties.Settings>
<setting name="MySetting" serializeAs="String">
<value>MyDefaultValue</value>
</setting>
</MyProject.Properties.Settings>
</applicationSettings>
要回答您的问题:您可以在应用程序部署中忽略包括app.config的默认设置,
To answer your question: You can omit including the app.config from your application deployment, the defaults that you provided when configuring the settings are hardcoded.
编辑:
只需注意您实际上想从程序集中读取 entire app.config。
可能的方法如下:
Just noticed you actually want to read the entire app.config from your assembly.A possible approach could be the following:
// 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");
// ...
这篇关于将没有app.config文件的硬编码配置添加到某些程序集中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!