RegistryUtil.cs
上传用户:nnpulika
上传日期:2013-02-15
资源大小:597k
文件大小:2k
源码类别:

状态条

开发平台:

C#

  1. using System;
  2. using Microsoft.Win32;
  3. namespace UtilityLibrary.Win32
  4. {
  5. /// <summary>
  6. /// Summary description for Registry.
  7. /// </summary>
  8. public class RegistryUtil
  9. {
  10. #region Constructors
  11. // No need to constructo this object
  12. private RegistryUtil()
  13. {
  14. }
  15. #endregion
  16. #region Implementation
  17. static public void WriteToRegistry(RegistryKey RegHive, string RegPath, string KeyName, string KeyValue)
  18. {
  19. // Split the registry path 
  20. string[] regStrings;
  21.     regStrings = RegPath.Split('\'); 
  22. // First item of array will be the base key, so be carefull iterating below
  23. RegistryKey[] RegKey = new RegistryKey[regStrings.Length + 1]; 
  24. RegKey[0] = RegHive; 
  25.   
  26. for( int i = 0; i < regStrings.Length; i++ )
  27. RegKey[i + 1] = RegKey[i].OpenSubKey(regStrings[i], true);
  28. // If key does not exist, create it
  29. if (RegKey[i + 1] == null)  
  30. {
  31. RegKey[i + 1] = RegKey[i].CreateSubKey(regStrings[i]);
  32. }
  33. // Write the value to the registry
  34. try
  35. {
  36. RegKey[regStrings.Length].SetValue(KeyName, KeyValue);     
  37. }
  38. catch (System.NullReferenceException)
  39. {
  40. throw(new Exception("Null Reference"));
  41. }
  42. catch (System.UnauthorizedAccessException)
  43. {
  44.      throw(new Exception("Unauthorized Access"));
  45. }
  46. }
  47. static public string ReadFromRegistry(RegistryKey RegHive, string RegPath, string KeyName, string DefaultValue)
  48. {
  49. string[] regStrings;
  50. string result = ""; 
  51. regStrings = RegPath.Split('\');
  52. //First item of array will be the base key, so be carefull iterating below
  53. RegistryKey[] RegKey = new RegistryKey[regStrings.Length + 1]; 
  54. RegKey[0] = RegHive; 
  55. for( int i = 0; i < regStrings.Length; i++ )
  56. {
  57. RegKey[i + 1] = RegKey[i].OpenSubKey(regStrings[i]);
  58. if (i  == regStrings.Length - 1 )
  59. {
  60. result = (string)RegKey[i + 1].GetValue(KeyName, DefaultValue); 
  61. }
  62. return result; 
  63. }  
  64. #endregion
  65. }
  66. }