Add hardcoded configuration without app.config file to some assembly

主宰稳场 提交于 2019-12-13 02:23:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!