RegistUtils.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using CommonLang;
  2. using Microsoft.Win32;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. namespace CommonFroms
  9. {
  10. public static class RegistUtils
  11. {
  12. /// <summary>
  13. /// 从注册表里读取信息
  14. /// </summary>
  15. /// <typeparam name="T"></typeparam>
  16. /// <param name="key"></param>
  17. /// <param name="value"></param>
  18. /// <returns></returns>
  19. public static bool TryGetAppRegistry<T>(string key, out T value)
  20. {
  21. return TryGetAppRegistry<T>(null, key, out value);
  22. }
  23. /// <summary>
  24. /// 在注册表里写入信息
  25. /// </summary>
  26. /// <typeparam name="T"></typeparam>
  27. /// <param name="key"></param>
  28. /// <param name="value"></param>
  29. public static void PutAppRegistry<T>(string key, T value)
  30. {
  31. PutAppRegistry<T>(null, key, value);
  32. }
  33. /// <summary>
  34. /// 从注册表里读取信息
  35. /// </summary>
  36. /// <typeparam name="T"></typeparam>
  37. /// <param name="path">应用子目录</param>
  38. /// <param name="key"></param>
  39. /// <param name="value"></param>
  40. /// <returns></returns>
  41. public static bool TryGetAppRegistry<T>(string path, string key, out T value)
  42. {
  43. RegistryKey masterKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\" + Application.CompanyName + "\\" + Application.ProductName + ((path != null) ? ("\\" + path) : ("")));
  44. try
  45. {
  46. if (masterKey != null)
  47. {
  48. object obj = masterKey.GetValue(key);
  49. if (obj != null)
  50. {
  51. value = (T)Parser.StringToObject(obj.ToString(), typeof(T));
  52. return true;
  53. }
  54. }
  55. }
  56. finally
  57. {
  58. masterKey.Close();
  59. }
  60. value = default(T);
  61. return false;
  62. }
  63. /// <summary>
  64. /// 在注册表里写入信息
  65. /// </summary>
  66. /// <typeparam name="T"></typeparam>
  67. /// <param name="path">应用子目录</param>
  68. /// <param name="key"></param>
  69. /// <param name="value"></param>
  70. public static void PutAppRegistry<T>(string path, string key, T value)
  71. {
  72. RegistryKey masterKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\" + Application.CompanyName + "\\" + Application.ProductName + ((path != null) ? ("\\" + path) : ("")));
  73. try
  74. {
  75. if (masterKey != null)
  76. {
  77. masterKey.SetValue(key, Parser.ObjectToString(value));
  78. }
  79. }
  80. finally
  81. {
  82. masterKey.Close();
  83. }
  84. }
  85. }
  86. }