Introduction
If you ever wanted to use a .NET settings file (e.g., Settings.settings
) in your library
or put settings in an external configuration file (e.g., ExternalSettings.config), then this article is for you.
I've been using library assembly configuration files (e.g., MyLib.dll.config) for a while and I must say they have their purpose (despite what Microsoft may tell you).
Occasionally, I also need to use constants in my libraries and while they might never change, I feel more comfortable when putting them in a configuration file.
Using a .NET settings file is the most convenient way to do that in my opinion.
Using the code
Library configuration file
Using the code is very simple. First add a reference to AssemblySettings.dll and then follow these steps:
- Add a settings file to your library project (you may already have a default settings file "Properties\Settings.settings").
- Add a
partial
class with the same name as your settings file. For example, if your file is named "Settings.settings"
then add a class named Settings
in the file Settings.cs. - Add the following constructor to the
partial
class:
partial class Settings
{
Settings() : base(new ConfigurationFileApplicationSettings(
Assembly.GetExecutingAssembly(),
typeof(Settings)
)) { }
}
VoilĂ ! Your settings will be loaded from the configuration file of the library assembly.
Caveats
When you compile your library in Visual Studio, your "App.config" file will be copied to the output directory and named after the name
of your library (e.g., MyLib.dll.config). However, if you add a reference to your library from another project, the ".config" file will
not be copied to that project's output directory. You must do that manually or by using some deployment technique.
One way to do this automatically from VS is to create a copy of the "App.config" file in your project and name it "MyLib.dll.config".
Then edit the file's properties and set "Build Action" to "Content" and "Copy to Output Directory" to "Copy if newer".
Since the file is a content file, it will follow your library wherever it goes :-).
External configuration file
If you want to keep your settings in an external configuration file in a class library or a .exe project, you can do that as well.
The only difference is that you must place the name of your ".config" file instead of Assembly.GetExecutingAssembly()
in the above code.
partial class Settings
{
Settings() : base(new ConfigurationFileApplicationSettings(
"ExternalSettings.config",
typeof(Settings)
)) { }
}
Final thoughts
Using class library configuration files could be very convenient in some cases. Being unable to do so out of the box is another example of Microsoft thinking on the behalf of developers.
To "Microsoft": give us tools. We known how to handle them ;-).