Home
Manage Your Code
Snippet: AssemblySettings (C#)
Title: AssemblySettings Language: C#
Description: Allows you to use per-assembly configuration files with appSettings-like configuration elements. Views: 522
Author: Dave Donaldson Date Added: 4/10/2007
Copy Code  
1// ---------------------------------------------------------------------------------

2// This class was originally obtained from Mike Woodring of DevelopMentor. He has

3// written several utilities that are available for free download from his site,

4// which is located at http://www.bearcanyon.com/dotnet/ (under the Configuration

5// section is a link for "Per-Assembly Configuration Files").

6//

7// Usage:

8//     AssemblySettings settings = new AssemblySettings();

9//     string someSetting1 = settings["someKey1"];

10//     string someSetting2 = settings["someKey2"];

11// ---------------------------------------------------------------------------------

12
13using System;
14using System.Reflection;
15using System.Collections;
16using System.Xml;
17using System.Configuration;
18using System.Runtime.CompilerServices;
19
20public class AssemblySettings
21{
22    private IDictionary _dicSettings;
23
24    [MethodImpl(MethodImplOptions.NoInlining)]
25    public AssemblySettings()
26        : this(Assembly.GetCallingAssembly())
27    {
28    }
29
30    public AssemblySettings(Assembly assembly)
31    {
32        _dicSettings = GetConfig(assembly);
33    }
34
35    public string this[string key]
36    {
37        get
38        {
39            string settingValue = null;
40
41            if (_dicSettings != null)
42            {
43                settingValue = _dicSettings[key] as string;
44            }
45
46            return (settingValue == null ? string.Empty : settingValue);
47        }
48    }
49
50    public static IDictionary GetConfig()
51    {
52        return GetConfig(Assembly.GetCallingAssembly());
53    }
54
55    public static IDictionary GetConfig(Assembly assembly)
56    {
57        // Open and parse configuration file for specified

58        // assembly, returning collection to caller for future

59        // use outside of this class.

60
61        string configFile = assembly.CodeBase + ".config";
62        const string nodeName = "assemblySettings";
63
64        XmlDocument doc = new XmlDocument();
65        doc.Load(new XmlTextReader(configFile));
66
67        XmlNodeList nodes = doc.GetElementsByTagName(nodeName);
68
69        foreach (XmlNode node in nodes)
70        {
71            if (node.LocalName == nodeName)
72            {
73                DictionarySectionHandler handler = new DictionarySectionHandler();
74                return (IDictionary)handler.Create(null, null, node);
75            }
76        }
77
78        // Otherwise

79        return null;
80    }
81}
Usage
AssemblySettings settings = new AssemblySettings();
string mySetting = settings["MyKey"];
Notes
// Make sure something like this is in your config file