My registry Class

Nice Registry Class in C#

Will be posting article on how to create simple application, with full working code in C#
And welcome to anyone who want to post their own article
Post Reply
User avatar

Topic author
Superl
Site Admin
Site Admin
Posts: 1267
Joined: Sat Apr 16, 2011 7:49 am
Location: Montreal, Canada
Contact:

My registry Class

#2759

Post by Superl » Tue Feb 06, 2018 9:11 am

MyRegistry Class C# Introduction:

This is the class I created for my registry function, this class will test if your running a 64 bit OS and will work. It also contain a class for backing up and restore the registry.
  1. #region Disclaimer
  2.  
  3. //  ****************************************************************************************************
  4. // Assembly        : MyRegistry
  5. // Author            : Luc Joly
  6. // Created          : 01-27-2018
  7. // Assembly        : MyRegistry
  8. //
  9. //  Last Modified By : Luc Joly
  10. //  Last Modified On : 02-03-2018 : 10:45 PM
  11. //  ****************************************************************************************************
  12. //  ****************************************************************************************************
  13. // <copyright file="MyRegistry.cs" company="LuJoSoft">
  14. // Any distribution of source code without approval of LuJoSoft is prohibited.    
  15. // Copyright ©  2018. LuJoSoft. All rights reserved.
  16. // </copyright>
  17. // <summary>
  18. // Source Code and Executable Files can be used in commercial applications
  19. // Source Code and Executable Files can be redistributed; and Source Code
  20. // can be modified to create derivative works  only with the Author's consent;
  21. // </summary>
  22. //  ****************************************************************************************************
  23.  
  24. #endregion
  25.  
  26. using System;
  27. using System.Diagnostics;
  28. using System.IO;
  29. using System.Runtime.InteropServices;
  30. using System.Text;
  31. using LJBaseLibrary.LJErrorLog;
  32. using Microsoft.Win32;
  33.  
  34. namespace MyRegistry
  35. {
  36.     /// <summary>
  37.     ///     Enumerate the different hive of the registry
  38.     /// </summary>
  39.     public enum EnumHive
  40.     {
  41.         /// <summary>
  42.         ///     The local machine
  43.         /// </summary>
  44.         LocalMachine,
  45.  
  46.         /// <summary>
  47.         ///     The current user
  48.         /// </summary>
  49.         CurrentUser,
  50.  
  51.         /// <summary>
  52.         ///     The classes root
  53.         /// </summary>
  54.         ClassesRoot,
  55.  
  56.         /// <summary>
  57.         ///     The current configuration
  58.         /// </summary>
  59.         CurrentConfig,
  60.  
  61.         /// <summary>
  62.         ///     The user
  63.         /// </summary>
  64.         User
  65.     }
  66.  
  67.     /// <summary>
  68.     ///     A registry helper class.
  69.     /// </summary>
  70.     public class MyRegistry
  71.     {
  72.         /// <summary>
  73.         ///     Log error
  74.         /// </summary>
  75.         private static readonly ErrorLog Logger = new ErrorLog();
  76.  
  77.         #region registry normal function
  78.  
  79.         /// <summary>
  80.         /// Get registry hive to work with.
  81.         /// </summary>
  82.         /// <param name="hive">The hive.</param>
  83.         /// <returns>
  84.         /// The <see cref="RegistryKey" />.
  85.         /// </returns>
  86.         internal static RegistryKey GetRegistryKey(EnumHive hive)
  87.         {
  88.             switch (hive)
  89.             {
  90.                 case EnumHive.LocalMachine:
  91.                     return RegistryKey.OpenBaseKey(
  92.                         RegistryHive.LocalMachine,
  93.                         Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32);
  94.  
  95.                 case EnumHive.CurrentUser:
  96.                     return RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32);
  97.  
  98.                 case EnumHive.ClassesRoot:
  99.                     return RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry32);
  100.  
  101.                 case EnumHive.CurrentConfig:
  102.                     return RegistryKey.OpenBaseKey(RegistryHive.CurrentConfig, RegistryView.Registry32);
  103.  
  104.                 case EnumHive.User:
  105.                     return RegistryKey.OpenBaseKey(RegistryHive.Users, RegistryView.Registry32);
  106.  
  107.                 default:
  108.                     return null;
  109.             }
  110.         }
  111.  
  112.         /// <summary>
  113.         /// Return true if the key exist
  114.         /// </summary>
  115.         /// <param name="keyPath">Path of the key to check</param>
  116.         /// <param name="hive">The registry hive to check</param>
  117.         /// <returns>
  118.         /// The <see cref="bool" />.
  119.         /// </returns>
  120.         internal bool CheckRegistry(string keyPath, EnumHive hive)
  121.         {
  122.             try
  123.             {
  124.                 using (var regkey = GetRegistryKey(hive))
  125.                 {
  126.                     return regkey.OpenSubKey(keyPath) != null;
  127.                 }
  128.             }
  129.             catch
  130.             {
  131.                 return false;
  132.             }
  133.         }
  134.  
  135.         /// <summary>
  136.         /// Get registry value return object.
  137.         /// </summary>
  138.         /// <param name="keyPath">Path of the key to check</param>
  139.         /// <param name="keyName">The key name.</param>
  140.         /// <param name="hive">The hive.</param>
  141.         /// <returns>
  142.         /// The <see cref="object" />.
  143.         /// </returns>
  144.         internal object GetRegistryValue(string keyPath, string keyName, EnumHive hive)
  145.         {
  146.             try
  147.             {
  148.                 using (var regkey = GetRegistryKey(hive))
  149.                 {
  150.                     if (regkey == null) return null;
  151.                     using (var regkey2 = regkey.OpenSubKey(keyPath))
  152.                     {
  153.                         return regkey2?.GetValue(keyName);
  154.                     }
  155.                 }
  156.             }
  157.             catch (Exception ex)
  158.             {
  159.                 MyMessage.Show(ex.Message);
  160.                 Logger.LogError(ex);
  161.                 return false;
  162.             }
  163.         }
  164.  
  165.         /// <summary>
  166.         /// Write to the registry and return tue if successfull.
  167.         /// </summary>
  168.         /// <param name="keyPath">Path of the key to check</param>
  169.         /// <param name="hive">The hive.</param>
  170.         /// <returns>
  171.         /// The <see cref="bool" />.
  172.         /// </returns>
  173.         internal bool WriteRegistry(string keyPath, EnumHive hive)
  174.         {
  175.             try
  176.             {
  177.                 using (var regkey = GetRegistryKey(hive))
  178.                 {
  179.                     if (regkey == null) return false;
  180.                     regkey.CreateSubKey(keyPath, false);
  181.                 }
  182.  
  183.                 return true;
  184.             }
  185.             catch (Exception ex)
  186.             {
  187.                 Logger.LogError(ex);
  188.                 return false;
  189.             }
  190.         }
  191.  
  192.         /// <summary>
  193.         /// Write to the registry and return tue if successfull.
  194.         /// </summary>
  195.         /// <param name="keyPath">Path of the key to check</param>
  196.         /// <param name="keyName">The key name.</param>
  197.         /// <param name="keyValue">The key value.</param>
  198.         /// <param name="hive">The hive.</param>
  199.         /// <returns>
  200.         /// The <see cref="bool" />.
  201.         /// </returns>
  202.         internal bool WriteRegistry(string keyPath, string keyName, object keyValue, EnumHive hive)
  203.         {
  204.             try
  205.             {
  206.                 using (var regkey = GetRegistryKey(hive))
  207.                 {
  208.                     if (regkey == null) return false;
  209.                     regkey.CreateSubKey(keyPath, true);
  210.  
  211.                     using (var regkey2 = regkey.OpenSubKey(keyPath, true))
  212.                     {
  213.                         if (regkey2 == null) return false;
  214.                         regkey2.SetValue(keyName, keyValue);
  215.                     }
  216.                 }
  217.  
  218.                 return true;
  219.             }
  220.             catch (Exception ex)
  221.             {
  222.                 Logger.LogError(ex);
  223.                 return false;
  224.             }
  225.         }
  226.  
  227.         /// <summary>
  228.         /// Write to the registry and return tue if successfull.
  229.         /// </summary>
  230.         /// <param name="keyPath">Path of the key to check</param>
  231.         /// <param name="keyName">The key name.</param>
  232.         /// <param name="keyValue">The key value.</param>
  233.         /// <param name="hive">The hive.</param>
  234.         /// <param name="valueKind">The RegistryValueKind value kind.</param>
  235.         /// <returns>
  236.         /// The <see cref="bool" />.
  237.         /// </returns>
  238.         internal bool WriteRegistry(string keyPath, string keyName, object keyValue, EnumHive hive, RegistryValueKind valueKind)
  239.         {
  240.             try
  241.             {
  242.                 using (var regkey = GetRegistryKey(hive))
  243.                 {
  244.                     if (regkey == null) return false;
  245.                     regkey.CreateSubKey(keyPath, true);
  246.                     using (var regkey2 = regkey.OpenSubKey(keyPath, true))
  247.                     {
  248.                         if (regkey2 == null) return false;
  249.                         regkey2.SetValue(keyName, keyValue, valueKind);
  250.                     }
  251.                 }
  252.  
  253.                 return true;
  254.             }
  255.             catch (Exception ex)
  256.             {
  257.                 Logger.LogError(ex);
  258.                 return false;
  259.             }
  260.         }
  261.  
  262.         /// <summary>
  263.         /// The delete key registry.
  264.         /// </summary>
  265.         /// <param name="keyPath">Path of the key to check</param>
  266.         /// <param name="keyName">The key name to delete</param>
  267.         /// <param name="hive">The registry hive to delete the key.</param>
  268.         /// <returns>
  269.         /// The <see cref="bool" />.
  270.         /// </returns>
  271.         internal bool DeleteKeyRegistry(string keyPath, string keyName, EnumHive hive)
  272.         {
  273.             try
  274.             {
  275.                 using (var regkey = GetRegistryKey(hive))
  276.                 {
  277.                     if (regkey == null) return false;
  278.                     using (var regkey2 = regkey.OpenSubKey(keyPath, true))
  279.                     {
  280.                         if (regkey2 == null) return false;
  281.                         regkey2.DeleteValue(keyName, true);
  282.                     }
  283.                 }
  284.                 return true;
  285.             }
  286.             catch (Exception ex)
  287.             {
  288.                 Logger.LogError(ex);
  289.                 return false;
  290.             }
  291.         }
  292.  
  293.         /// <summary>
  294.         /// Delete registry tree.
  295.         /// </summary>
  296.         /// <param name="keyPath">Path of the key to check</param>
  297.         /// <param name="keyName">Name of the key.</param>
  298.         /// <param name="hive">The registry hive to delete the key.</param>
  299.         /// <returns>
  300.         /// The <see cref="bool" />.
  301.         /// </returns>
  302.         internal bool DeleteRegistryTree(string keyPath, string keyName, EnumHive hive)
  303.         {
  304.             try
  305.             {
  306.                 using (var regkey = GetRegistryKey(hive))
  307.                 {
  308.                     if (regkey == null) return false;
  309.                     using (var regkey2 = regkey.OpenSubKey(keyPath, true))
  310.                     {
  311.                         if (regkey2 == null) return false;
  312.                         regkey2.DeleteSubKeyTree(keyName, true);
  313.                     }
  314.                 }
  315.  
  316.                 return true;
  317.             }
  318.             catch (Exception ex)
  319.             {
  320.                 MyMessage.Show(ex.Message);
  321.                 Logger.LogError(ex);
  322.                 return false;
  323.             }
  324.         }
  325.  
  326.         #endregion registry normal function
  327.  
  328.         #region Export and import registry key
  329.  
  330.         /// <summary>
  331.         /// Gets the short name of the path.
  332.         /// </summary>
  333.         /// <param name="lpszLongPath">The LPSZ long path.</param>
  334.         /// <param name="lpszShortPath">The LPSZ short path.</param>
  335.         /// <param name="cchBuffer">The CCH buffer.</param>
  336.         /// <returns></returns>
  337.         [DllImport("kernel32", EntryPoint = "GetShortPathNameA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
  338.         private static extern int GetShortPathName([MarshalAs(UnmanagedType.VBByRefStr)] ref string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);
  339.  
  340.         /// <summary>
  341.         /// Exports the key.
  342.         /// </summary>
  343.         /// <param name="sRegKeyPath">The s reg key path.</param>
  344.         /// <param name="sfile">The sfile.</param>
  345.         public void ExportKey(string sRegKeyPath, string sfile)
  346.         {
  347.             var text1 = "\"" + sRegKeyPath + "\"";
  348.             FileAppend(sfile, "");
  349.             ExecuteRegistry("regedit.exe", "/E " + GetDosPath(sfile) + " " + text1, ProcessWindowStyle.Normal);
  350.         }
  351.  
  352.         /// <summary>
  353.         /// Files the append.Append the Path Of The Key
  354.         /// </summary>
  355.         /// <param name="path">The path.</param>
  356.         /// <param name="text">The text.</param>
  357.         public static void FileAppend(string path, string text)  
  358.         {
  359.             var writer1 = File.AppendText(path);
  360.             writer1.Write(text);
  361.             writer1.Close();
  362.         }
  363.  
  364.         /// <summary>
  365.         /// Gets the dos path. This will Return the Dos Command Path
  366.         /// </summary>
  367.         /// <param name="path">The path.</param>
  368.         /// <returns></returns>
  369.         public static string GetDosPath(string path)  
  370.         {
  371.             return GetShortFileName(path);
  372.         }
  373.  
  374.         public static string GetShortFileName(string path)
  375.         {
  376.             var builder1 = new StringBuilder(0x400);
  377.             var num1 = GetShortPathName(ref path, builder1, builder1.Capacity);
  378.             return builder1.ToString(0, num1);
  379.         }
  380.  
  381.  
  382.         /// <summary>
  383.         /// Executes the backup of the registry.
  384.         /// </summary>
  385.         /// <param name="path">The path.</param>
  386.         /// <param name="arguments">The arguments.</param>
  387.         /// <param name="style">The style.</param>
  388.         /// <returns></returns>
  389.         public static bool ExecuteRegistry(string path, string arguments, ProcessWindowStyle style)
  390.         {
  391.             var proc = new Process();
  392.             try
  393.             {
  394.                 proc.StartInfo.FileName = path;
  395.                 proc.StartInfo.UseShellExecute = false;
  396.                 proc = Process.Start(path, arguments);
  397.                 proc?.WaitForExit();
  398.                 return true;
  399.             }
  400.             catch (Exception ex)
  401.             {
  402.                 Logger.LogError(ex);
  403.                 return false;
  404.             }
  405.             finally
  406.             {
  407.                 proc?.Dispose();
  408.             }
  409.            
  410.         }
  411.  
  412.         /// <summary>
  413.         /// Restores the key to the registry.
  414.         /// </summary>
  415.         /// <param name="files">The files.</param>
  416.         /// <returns></returns>
  417.         public bool RestoreKey(string files)
  418.         {
  419.             var path = " /S " + "\"" + files + "\"";
  420.             var proc = new Process();
  421.             try
  422.             {
  423.                 proc = Process.Start("regedit.exe", path);
  424.                 proc?.WaitForExit();
  425.                 return true;
  426.             }
  427.             catch (Exception ex)
  428.             {
  429.                 Logger.LogError(ex);
  430.                 return false;
  431.             }
  432.             finally
  433.             {
  434.                 proc?.Dispose();
  435.             }
  436.  
  437.         }
  438.  
  439.         #endregion Export and import registry key
  440.     }
  441. }




Usage
  1.  private readonly MyRegistry _registryHelper = new MyRegistry();
  2.  
  3. // To use it to write
  4.  if (_registryHelper.WriteRegistry(
  5.     keyPath,
  6.     keyName,
  7.     valueToSet,
  8.     EnumHive.CurrentUser,                            
  9.     RegistryValueKind.Binary))
  10.  
  11. // Also to write a string you don't need RegistryValueKind
  12.  if (_registryHelper.WriteRegistry(
  13.     keyPath,
  14.     keyName,
  15.     valueToSet,
  16.     EnumHive.ClassesRoot))
  17.  
  18. // Also to write just a key then use it like this
  19.  if (_registryHelper.WriteRegistry(
  20.     keyPath,     
  21.     EnumHive.ClassesRoot))
  22.  
  23. // Check if a key exist
  24. if (_registryHelper.CheckRegistry(keyPath, EnumHive.ClassesRoot))
  25.  
  26. // To delete a key tree
  27. if (_registryHelper.DeleteRegistryTree(keyPath, keyName, EnumHive.ClassesRoot))
  28.  
  29. // To delete a key
  30. if (_registryHelper.DeleteKeyRegistry(keyPath, keyName, EnumHive.CurrentUser))
  31.  
  32. // Get value of key
  33. var valu = _registryHelper.GetRegistryValue(keyPath, keyName, EnumHive.LocalMachine);
  34.  
  35. // To backup branch of the registry
  36. var backup = Path.Combine(folder, "Part3.reg");
  37. _registryHelper.ExportKey("HKEY_CURRENT_USER", backup);
  38.  
  39. // To backup branch of the registry
  40. _registryHelper.RestoreKey(file.reg) // Must be the full path
  41.  
  42.  
  43.  
  44.  


MyRegistry.cs
MyRegistry
(14.6 KiB) Downloaded 138 times
MyRegistry.cs
MyRegistry
(14.6 KiB) Downloaded 138 times


Enjoy!
Superl :ympeace:


Come and say hello in here
Any donation will help click here please.

Have a nice day :103:

Post Reply

Return to “Coding Forum”

Who is online

Users browsing this forum: No registered users and 1 guest