AppSettingsReader.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // System.Configuration.AppSettingsReader
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002 Ximian, Inc (http://www.ximian.com)
  8. //
  9. using System.Reflection;
  10. using System.Collections.Specialized;
  11. namespace System.Configuration
  12. {
  13. public class AppSettingsReader
  14. {
  15. NameValueCollection appSettings;
  16. public AppSettingsReader ()
  17. {
  18. appSettings = ConfigurationSettings.AppSettings;
  19. }
  20. public object GetValue (string key, Type type)
  21. {
  22. if (key == null)
  23. throw new ArgumentNullException ("key");
  24. if (type == null)
  25. throw new ArgumentNullException ("type");
  26. string value = appSettings [key];
  27. if (value == null)
  28. throw new InvalidOperationException ("'" + key + "' could not be found.");
  29. if (type == typeof (string))
  30. return value.Substring (1, value.Length - 2);
  31. MethodInfo parse = type.GetMethod ("Parse", new Type [] {typeof (string)});
  32. if (parse == null)
  33. throw new InvalidOperationException ("Type " + type + " does not have a Parse method");
  34. object result = null;
  35. try {
  36. result = parse.Invoke (null, new object [] {value});
  37. } catch (Exception e) {
  38. throw new InvalidOperationException ("Parse error.", e);
  39. }
  40. return result;
  41. }
  42. }
  43. }