Free mag vol1 | Page 610

CHAPTER 14  BUILDING AND CONFIGURING CLASS LIBRARIES The System.Configuration Namespace Currently, all of the *.config files shown in this chapter have made use of well-known XML elements that are read by the CLR to resolve the location of external assemblies. In addition to these recognized elements, it is perfectly permissible for a client configuration file to contain application-specific data that has nothing to do with binding heuristics. Given this, it should come as no surprise that the .NET Framework provides a namespace that allows you to programmatically read the data within a client configuration file. The System.Configuration namespace provides a small set of types you can use to read custom data from a client’s *.config file. These custom settings must be contained within the scope of an element. The element contains any number of elements that define key/value pairs to be obtained programmatically. For example, assume you have an App.config file for a Console Application named AppConfigReaderApp that defines two application specific values, listed like so: Reading these values for use by the client application is as simple as calling the instance-level GetValue() method of the System.Configuration.AppSettingsReader type. As shown in the following code, the first parameter to GetValue() is the name of the key in the *.config file, whereas the second parameter is the underlying type of the key (obtained via the C# typeof operator): using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.Threading.Tasks; using System.Configuration; namespace AppConfigReaderApp { class Program { static void Main(string[] args) { Console.WriteLine("***** Reading Data *****\n"); // Get our custom data from the *.config file. AppSettingsReader ar = new AppSettingsReader(); int numbOfTimes = (int)ar.GetValue("RepeatCount", typeof(int)); 552