问题
I need to add configuration information to the assembly itself without including its app.config file with it. How can i do it?
EDIT: 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
回答1:
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.
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");
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>
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.
Edit:
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");
// ...
回答2:
you can have a custom XML file where you store your settings and then you set it as Embedded resource so it will be available inside the exe or dll.
see here: How can I retrieve an embedded xml resource? for an example on how to read it at runtime
Edit: and to load it as custom configuration file check here: Loading custom configuration files
来源:https://stackoverflow.com/questions/7785803/add-hardcoded-configuration-without-app-config-file-to-some-assembly