Geeks With Blogs

News My Blog has been MOVED to https://mfreidge.wordpress.com
Michael Freidgeim's OLD Blog My Blog has been MOVED to https://mfreidge.wordpress.com

I wanted to export registry in C# .Net project. First of all I noticed that the Microsoft.Win32.Registry doesnt' provide this function.
I've searched a web and found VB.NET implementation at http://www.controlled-insanity.com/Forum/viewtopic.php?p=58715&sid=6cb99f5471bc3e916896443cd0f9f26e.

Unfortunately the code calls a few functions that were not included on the page and I wrote  ( or copied from others web sites) them to make the code compilable.

Because my particular project is in C# and I didn't want to have additional DLL, I used .Net Reflector to convert VB class to C#.
A few disasssembled functions in C# were not compilable and looked very ugly.

I've noticed that vb On Error Resume Next  causes  .Net Reflector  to generate not compilable C# code.

So I commented out On Error Resume Next  , which is a good idea anyway, recompile VB code and disaccemble it as C# code, fixed some VB/C# discrepencies and make the C# class working.

At the end I understood that to export the registry the class I just need to Process.Start regedit.exe with corresponding parameters, so I didn't need most of the code.

However I will post the whole class here. Note that I  tested only ExportKey method of the class.

 

//'http://www.controlled-insanity.com/Forum/viewtopic.php?p=58715&sid=6cb99f5471bc3e916896443cd0f9f26e

namespace ModRegistry

{

    using Microsoft.VisualBasic;

    using Microsoft.VisualBasic.CompilerServices;

    using Microsoft.Win32;

    using System;

    using System.Diagnostics;

    using System.IO;

    using System.Runtime.InteropServices;

    using System.Text;

 

//   [StandardModule]

    public sealed class RegistryHelper

    {

 

            //    'Just a wee bit of API to fill the gaps not covered by .NET's registry access

            //    'Used to determine a value's type and read/write strings of the type REG_EXPAND_SZ

            [DllImport("advapi32.dll", CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]

            private static extern int RegCloseKey(int hKey);

 

            [DllImport("advapi32.dll", EntryPoint="RegCreateKeyA", CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]

            private static extern int RegCreateKey(int hKey, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpSubKey, ref int phkResult);

 

            [DllImport("advapi32.dll", EntryPoint="RegOpenKeyA", CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]

            private static extern int RegOpenKey(int hKey, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpSubKey, ref int phkResult);

 

            [DllImport("advapi32.dll", EntryPoint="RegQueryValueExA", CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]

            private static extern int RegQueryValueEx(int hKey, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpValueName, int lpReserved, ref int lpType, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpData, ref int lpcbData);

 

            [DllImport("advapi32.dll", EntryPoint="RegSetValueExA", CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]

            private static extern int RegSetValueEx(int hKey, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpValueName, int Reserved, int dwType, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpData, int cbData);

 

 

            // Methods

 

        public static bool CreateKey(RegistryKey hKey, string strPath, string NewKeyName)

        {

            bool flag1=false;

            RegistryKey key1 = hKey.OpenSubKey(strPath, true);

            if (key1 != null)

            {

                key1.CreateSubKey(NewKeyName);

                key1.Close();

                flag1 = true;

            }

            return flag1;

        }

 

        public static bool DeleteKey(RegistryKey hKey, string strPath)

        {

            bool flag1=false;

            int num1=0;

             int num2=0;

            try

            {

                ProjectData.ClearProjectError();

                num2 = 1;

                hKey.DeleteSubKeyTree(strPath);

                flag1 = true;

            }

            catch (Exception obj1) //when (?)

            {

                Exception exception2 = (Exception) obj1;

                ProjectData.SetProjectError(exception2);

                Exception exception1 = exception2;

                if (num1 == 0)

                {

                    num1 = -1;

                    switch (num2)

                    {

                        case 1:

                        {

                            goto Label_0058;

                        }

                    }

                    throw;

                }

            }

        Label_0058:

            if (num1 != 0)

            {

                ProjectData.ClearProjectError();

            }

            return flag1;

        }

 

        public static bool DeleteValue(RegistryKey hKey, string strPath, string strValue)

        {

            bool flag1=false;

            RegistryKey key1 = hKey.OpenSubKey(strPath, true);

            if (key1 != null)

            {

                key1.DeleteValue(strValue);

                key1.Close();

                flag1 = true;

            }

            return flag1;

        }

 

        public static void ExportKey(RegistryKey rKey, string sfile)

        {

            RegistryHelper.ExportKey(rKey.Name, sfile);

        }

 

        public static void ExportKey(string sRegKeyPath, string sfile)

        {

            string text1 = "\"" + sRegKeyPath + "\"";

            RegistryHelper.FileAppend(sfile, "");

            RegistryHelper.ShellFile("regedit.exe", "/E " + RegistryHelper.GetDosPath(sfile) + " " + text1, ProcessWindowStyle.Normal);

        }

 

        public static void ExportKey(RegistryKey hKey, string strPath, string sfile)

        {

            string text1="";

            if (hKey == Registry.ClassesRoot)

            {

                text1 = @"HKEY_CLASSES_ROOT\";

            }

            else if (hKey == Registry.CurrentUser)

            {

                text1 = @"HKEY_CURRENT_USER\";

            }

            else if (hKey == Registry.LocalMachine)

            {

                text1 = @"HKEY_LOCAL_MACHINE\";

            }

            else if (hKey == Registry.Users)

            {

                text1 = @"HKEY_USERS\";

            }

            else if (hKey == Registry.CurrentConfig)

            {

                text1 = @"HKEY_CURRENT_CONFIG\";

            }

            else if (hKey == Registry.DynData)

            {

                text1 = @"HKEY_DYN_DATA\";

            }

            else if (hKey == Registry.PerformanceData)

            {

                text1 = @"HKEY_PERFORMANCE_DATA\";

            }

            RegistryHelper.ExportKey(text1, sfile);

//        '        FileAppend(sfile, "")

//        'mPath = Microsoft.VisualBasic.ControlChars.Quote & mPath & strPath & Microsoft.VisualBasic.ControlChars.Quote

//        'ShellFile("regedit.exe", "/E " & GetDosPath(sfile) & " " & mPath, 0)

        }

 

            public static string[] GetAllKeys(RegistryKey hKey, string strPath)

            {

                  string[] textArray1=null;

                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);

                  if (key1 != null)

                  {

                        textArray1 = key1.GetSubKeyNames();

                        key1.Close();

                  }

                  return textArray1;

            }

 

 

 

            public static bool GetAllValues(RegistryKey hKey, string strPath, ref string[] mNames)

            {

                  bool flag1=false;

                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);

                  if (key1 != null)

                  {

                        mNames = key1.GetValueNames();

                        flag1 = true;

                        key1.Close();

                  }

                  return flag1;

            }

 

 

        public static string GetDosPath(string path)

        {

            return RegistryHelper.GetShortFileName(path);

        }

 

        public static void GetRootKeyAndPath(string FullPath, ref RegistryKey Rootkey, ref string strPath)

        {

            if ((FullPath.Length != 0) && (FullPath.IndexOf(@"\") != -1))

            {

                string[] textArray1 = Strings.Split(FullPath, @"\", -1, CompareMethod.Binary);

                string text1 = RegistryHelper.AddBackslash(FullPath, @"\");

//        'tmp(0) is "My Computer"

//        'tmp(1) is the "Root" key - eg. "HKEY_CLASSES_ROOT"

                strPath = text1.Replace(textArray1[0] + @"\" + textArray1[1] + @"\", "");

//        'strPath is the path of the subkey

                string text2 = textArray1[1];//Determine the "Root" key

                if (StringType.StrCmp(text2, "HKEY_CLASSES_ROOT", false) == 0)

                {

                    Rootkey = Registry.ClassesRoot;

                }

                else if (StringType.StrCmp(text2, "HKEY_CURRENT_USER", false) == 0)

                {

                    Rootkey = Registry.CurrentUser;

                }

                else if (StringType.StrCmp(text2, "HKEY_LOCAL_MACHINE", false) == 0)

                {

                    Rootkey = Registry.LocalMachine;

                }

                else if (StringType.StrCmp(text2, "HKEY_USERS", false) == 0)

                {

                    Rootkey = Registry.Users;

                }

                else if (StringType.StrCmp(text2, "HKEY_CURRENT_CONFIG", false) == 0)

                {

                    Rootkey = Registry.CurrentConfig;

                }

                else if (StringType.StrCmp(text2, "HKEY_DYNDATA", false) == 0)

                {

                    Rootkey = Registry.DynData;

                }

                else if (StringType.StrCmp(text2, "HKEY_PERFORMANCE_DATA", false) == 0)

                {

                    Rootkey = Registry.PerformanceData;

                }

                strPath = RegistryHelper.RemoveBackslash(strPath);

            }

        }

 

        public static string GetRootKeyString(string FullPath)

        {

            string[] textArray1 = Strings.Split(FullPath, @"\", -1, CompareMethod.Binary);

            return textArray1[1];

        }

            public static string GetSafeKeyName(RegistryKey hKey, string strPath, string NewName, [Optional] bool AsNew /* = false */)

            {

                  string text1="";

                  int num1 = 1;

                  string text2 = NewName;

                  if (AsNew)

                  {

                        text2 = "New Key";

                        NewName = "New Key #1";

                  }

                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);

                  if (key1 == null)

                  {

                        return text1;

                  }

                  if (key1.SubKeyCount > 0)

                  {

                        string[] textArray1 = key1.GetSubKeyNames();

                        while (true)

                        {

                              bool flag1=false;

                              int num3 = key1.SubKeyCount - 1;

                              for (int num2 = 0; num2 <= num3; num2++)

                              {

                                    if (StringType.StrCmp(textArray1[num2], NewName, false) == 0)

                                    {

                                          flag1 = true;

                                          break;

                                    }

                              }

                              if (!flag1)

                              {

                                    text1 = NewName;

                                    goto Label_0096;

                              }

                              num1++;

                              flag1 = false;

                              NewName = text2 + " #" + StringType.FromInteger(num1);

                        }

                  }

                  text1 = NewName;

                  Label_0096:

                        key1.Close();

                  return text1;

            }

 

 

 

            public static string GetSafeValueName(RegistryKey hKey, string strPath, string NewName, [Optional] bool AsNew /* = false */)

            {

                  string text1="";

                  int num1 = 1;

                  string text2 = NewName;

                  if (AsNew)

                  {

                        text2 = "New Value";

                        NewName = "New Value #1";

                  }

                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);

                  if (key1 == null)

                  {

                        return text1;

                  }

                  if (key1.ValueCount > 0)

                  {

                        string[] textArray1 = key1.GetValueNames();

                        while (true)

                        {

                              bool flag1=false;

                              int num3 = key1.ValueCount - 1;

                              for (int num2 = 0; num2 <= num3; num2++)

                              {

                                    if (StringType.StrCmp(textArray1[num2], NewName, false) == 0)

                                    {

                                          flag1 = true;

                                          break;

                                    }

                              }

                              if (!flag1)

                              {

                                    text1 = NewName;

                                    goto Label_0096;

                              }

                              num1++;

                              flag1 = false;

                              NewName = text2 + " #" + StringType.FromInteger(num1);

                        }

                  }

                  text1 = NewName;

                  Label_0096:

                        key1.Close();

                  return text1;

            }

 

 

        public static byte[] GetSettingByte(ref RegistryKey hKey, ref string strPath, ref string strValue)

        {

            byte[] buffer1=null;

            RegistryKey key1 = hKey.OpenSubKey(strPath, true);

            if (key1 != null)

            {

                byte[] buffer2 = (byte[]) key1.GetValue(strValue, "");

                key1.Close();

                return buffer2;

            }

            return buffer1;

        }

 

        public static int GetSettingInteger(ref RegistryKey hKey, ref string strPath, ref string strValue)

        {

            RegistryKey key1 = hKey.OpenSubKey(strPath, true);

            if (key1 != null)

            {

                int num1 = IntegerType.FromObject(key1.GetValue(strValue, 0));

                key1.Close();

                return num1;

            }

            return -1;

        }

 

        public static string GetSettingString(RegistryKey hKey, string strPath, string strValue, [Optional] bool DontExpand /* = false */)

        {

            string text1="";

            int num6 = RegistryHelper.GetValueType(hKey, strPath, strValue);

            if (DontExpand | (num6 > 2))

            {

                        //            '.NET will automatically expand string values of the type REG_EXPAND_SZ

                        //            'It always likes to do the work for you ! Trouble is we want to see

                        //            'the data in it's raw form !!!

                        int num1=0;

                int num2=0;

                 int num3=0;

                 int num5=0;

                string text2="";

                if (hKey == Registry.ClassesRoot)

                {

                    num2 = -2147483648;

                }

                else if (hKey == Registry.CurrentUser)

                {

                    num2 = -2147483647;

                }

                else if (hKey == Registry.LocalMachine)

                {

                    num2 = -2147483646;

                }

                else if (hKey == Registry.Users)

                {

                    num2 = -2147483645;

                }

                else if (hKey == Registry.CurrentConfig)

                {

                    num2 = -2147483643;

                }

                else if (hKey == Registry.DynData)

                {

                    num2 = -2147483642;

                }

                else if (hKey == Registry.PerformanceData)

                {

                    num2 = -2147483644;

                }

                int num4 = RegistryHelper.RegOpenKey(num2, ref strPath, ref num1);

                num4 = RegistryHelper.RegQueryValueEx(num1, ref strValue, 0, ref num5, ref text2, ref num3);

                if (num4 == 0)

                {

                    text2 = new string(' ', num3);

                    int num7 = 0;

                    num4 = RegistryHelper.RegQueryValueEx(num1, ref strValue, 0, ref num7, ref text2, ref num3);

                    text1 = text2;

                }

                num4 = RegistryHelper.RegCloseKey(num1);

                return text1;

            }

            RegistryKey key1 = hKey.OpenSubKey(strPath, true);

            if (key1 != null)

            {

//            'If you don't need to see the REG_EXPAND_SZ in it's raw form

//            'then the above code is unneccessary thus the optional DontExpand

                text1 = StringType.FromObject(key1.GetValue(strValue, ""));

                if ((text1.Length == 0) & (strValue.Length == 0))

                {

//                'If it's the Default value and the result is "" then fill it in with "(value not set)"

                    text1 = "(value not set)";

                }

                key1.Close();

            }

            return text1;

        }

 

        public static int GetValueType(RegistryKey hKey, string strPath, string strValueName)

        {

//       'Appears to be a limitation in .NET Registry access - no method to determine value type

//        'I couldn't find any anyway.

//        'We have to resort to the API to provide us with the value type

 

                   int num2=0;

             int num3=0;

             int num5=0;

             int num7=0;

            if (hKey == Registry.ClassesRoot)

            {

                num3 = -2147483648;

            }

            else if (hKey == Registry.CurrentUser)

            {

                num3 = -2147483647;

            }

            else if (hKey == Registry.LocalMachine)

            {

                num3 = -2147483646;

            }

            else if (hKey == Registry.Users)

            {

                num3 = -2147483645;

            }

            else if (hKey == Registry.CurrentConfig)

            {

                num3 = -2147483643;

            }

            else if (hKey == Registry.DynData)

            {

                num3 = -2147483642;

            }

            else if (hKey == Registry.PerformanceData)

            {

                num3 = -2147483644;

            }

            strPath = RegistryHelper.RemoveBackslash(strPath);

            int num6 = RegistryHelper.RegOpenKey(num3, ref strPath, ref num2);

            string text2 = StringType.FromLong(0);

            num6 = RegistryHelper.RegQueryValueEx(num2, ref strValueName, 0, ref num7, ref text2, ref num5);

            num6 = RegistryHelper.RegCloseKey(num2);

            return num7;

        }

 

            public static bool HasSubKeys(RegistryKey hKey, string strPath)

            {

                  bool flag1=false;

                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);

                  if (key1 != null)

                  {

                        flag1 = key1.SubKeyCount > 0;

                        key1.Close();

                  }

                  return flag1;

            }

 

 

        public static void ImportKey(string sInFile)

        {

            RegistryHelper.ShellFile("regedit.exe", "/I /S " + RegistryHelper.GetDosPath(sInFile), ProcessWindowStyle.Normal);

        }

 

            public static bool IsKey(RegistryKey hKey, string strPath)

            {

                  bool flag1=false;

                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);

                  if (key1 != null)

                  {

                        flag1 = true;

                        key1.Close();

                  }

                  return flag1;

            }

 

 

            private static void RecurseAllSubKeyValues(RegistryKey hKey, string strPath, ref string[] ValuesColl)

            {

                  RegistryKey key1 = hKey.OpenSubKey(strPath, true);

                  if (key1 != null)

                  {

                        int num1;

                        string[] textArray1;

                        int num4;

                        int num3 = key1.ValueCount;

                        int num2 = key1.SubKeyCount;

                        if (num3 > 0)

                        {

                              textArray1 = key1.GetValueNames();

                              num1 = ValuesColl.GetUpperBound(0);

                              ValuesColl = (string[]) Utils.CopyArray((Array) ValuesColl, new string[(num1 + num3) + 1]);

                              int num6 = num3 - 1;

                              for (num4 = 0; num4 <= num6; num4++)

                              {

                                    ValuesColl[num1] = strPath + @"\" + textArray1[num4];

                                    num1++;

                              }

                        }

                        else

                        {

                              num1 = ValuesColl.GetUpperBound(0);

                              ValuesColl = (string[]) Utils.CopyArray((Array) ValuesColl, new string[(num1 + 1) + 1]);

                              ValuesColl[num1] = strPath + @"\";

                        }

                        if (num2 > 0)

                        {

                              textArray1 = key1.GetSubKeyNames();

                              int num5 = num3 - 1;

                              for (num4 = 0; num4 <= num5; num4++)

                              {

                                    RegistryHelper.RecurseAllSubKeyValues(hKey, strPath + @"\" + textArray1[num4], ref ValuesColl);

                              }

                        }

                        key1.Close();

                  }

            }

 

 

 

        public static bool RenameKey(RegistryKey hKey, string strPath, string NewKeyName)

        {

            bool flag1=false;

            string[] textArray1=null;

            string text4 = RegistryHelper.PathOnly(strPath);

            string text2 = RegistryHelper.FileOnly(strPath);

            string text1 = text4 + @"\" + NewKeyName;

            RegistryHelper.CreateKey(hKey, text4, NewKeyName);

            RegistryHelper.RecurseAllSubKeyValues(hKey, strPath, ref textArray1);

            if (textArray1.Length > 0)

            {

                int num5 = textArray1.GetUpperBound(0) - 1;

                for (int num3 = 0; num3 <= num5; num3++)

                {

                    string text7;

                    string text6 = RegistryHelper.FileOnly(textArray1[num3]);

                    string text5 = RegistryHelper.PathOnly(textArray1[num3]);

                    string text3 = text5.Replace(strPath, text1);

                    int num2 = RegistryHelper.GetValueType(hKey, text5, text6);

                    if (StringType.StrCmp(text6, "", false) == 0)

                    {

                        num2 = 1;

                    }

                    switch (num2)

                    {

                        case 1:

                        {

                            text7 = RegistryHelper.GetSettingString(hKey, text5, text6, false);

                            RegistryHelper.SaveSettingString(hKey, text3, text6, text7, SaveStringType.REG_SZ);

                            goto Label_014D;

                        }

                        case 2:

                        {

                            text7 = RegistryHelper.GetSettingString(hKey, text5, text6, false);

                            RegistryHelper.SaveSettingString(hKey, text3, text6, text7, SaveStringType.REG_EXPAND_SZ);

                            goto Label_014D;

                        }

                        case 3:

                        {

                            byte[] buffer1 = RegistryHelper.GetSettingByte(ref hKey, ref text5, ref text6);

                            RegistryHelper.SaveSettingByte(hKey, text3, text6, buffer1, false);

                            goto Label_014D;

                        }

                        case 4:

                        {

                            int num1 = RegistryHelper.GetSettingInteger(ref hKey, ref text5, ref text6);

                            RegistryHelper.SaveSettingInteger(hKey, text3, text6, num1);

                            goto Label_014D;

                        }

                        case 5:

                        case 6:

                        {

                            goto Label_014D;

                        }

                        case 7:

                        {

                            break;

                        }

                        default:

                        {

                            goto Label_014D;

                        }

                    }

                    text7 = RegistryHelper.GetSettingString(hKey, text5, text6, false);

                    RegistryHelper.SaveSettingString(hKey, text3, text6, text7, SaveStringType.REG_MULTI_SZ);

                Label_014D:;

                }

            }

            RegistryHelper.DeleteKey(hKey, strPath);

            return flag1;

        }

 

        public static bool RenameValue(RegistryKey hKey, string strPath, string strValue, string NewValueName)

        {

            bool flag1=false;

            string text1="";

            switch (RegistryHelper.GetValueType(hKey, strPath, strValue))

            {

                case 1:

                {

                    text1 = RegistryHelper.GetSettingString(hKey, strPath, strValue, false);

                    RegistryHelper.SaveSettingString(hKey, strPath, NewValueName, text1, SaveStringType.REG_SZ);

                    break;

                }

                case 2:

                {

                    text1 = RegistryHelper.GetSettingString(hKey, strPath, strValue, false);

                    RegistryHelper.SaveSettingString(hKey, strPath, NewValueName, text1, SaveStringType.REG_EXPAND_SZ);

                    break;

                }

                case 3:

                {

                    byte[] buffer1 = RegistryHelper.GetSettingByte(ref hKey, ref strPath, ref strValue);

                    RegistryHelper.SaveSettingByte(hKey, strPath, NewValueName, buffer1, false);

                    break;

                }

                case 4:

                {

                    int num1 = RegistryHelper.GetSettingInteger(ref hKey, ref strPath, ref strValue);

                    RegistryHelper.SaveSettingInteger(hKey, strPath, NewValueName, num1);

                    break;

                }

                case 7:

                {

                    text1 = RegistryHelper.GetSettingString(hKey, strPath, strValue, false);

                    RegistryHelper.SaveSettingString(hKey, strPath, NewValueName, text1, SaveStringType.REG_MULTI_SZ);

                    break;

                }

            }

            RegistryHelper.DeleteValue(hKey, strPath, strValue);

            return flag1;

        }

 

        public static bool SaveSettingByte(RegistryKey hKey, string strPath, string strValue, byte[] byteData, [Optional] bool SetEmpty /* = false */)

        {

            RegistryKey key1 = hKey.OpenSubKey(strPath, true);

            if (key1 == null)

            {

                bool flag1=false;

                return flag1;

            }

            if (SetEmpty)

            {

                key1.SetValue(strValue, 0);

            }

            else

            {

                key1.SetValue(strValue, byteData);

            }

            key1.Flush();

            key1.Close();

            return true;

        }

 

        public static void SaveSettingEmptyByte(RegistryKey hKey, string strPath, string strValueName)

        {

            int num1=0;

             int num2=0;

            if (hKey == Registry.ClassesRoot)

            {

                num2 = -2147483648;

            }

            else if (hKey == Registry.CurrentUser)

            {

                num2 = -2147483647;

            }

            else if (hKey == Registry.LocalMachine)

            {

                num2 = -2147483646;

            }

            else if (hKey == Registry.Users)

            {

                num2 = -2147483645;

            }

            else if (hKey == Registry.CurrentConfig)

            {

                num2 = -2147483643;

            }

            else if (hKey == Registry.DynData)

            {

                num2 = -2147483642;

            }

            else if (hKey == Registry.PerformanceData)

            {

                num2 = -2147483644;

            }

            int num3 = RegistryHelper.RegCreateKey(num2, ref strPath, ref num1);

            string text1 = StringType.FromLong(0);

            num3 = RegistryHelper.RegSetValueEx(num1, ref strValueName, 0, 3, ref text1, 0);

            num3 = RegistryHelper.RegCloseKey(num1);

        }

 

        public static bool SaveSettingInteger(RegistryKey hKey, string strPath, string strValue, int intData)

        {

            bool flag1=false;

            RegistryKey key1 = hKey.OpenSubKey(strPath, true);

            if (key1 != null)

            {

                key1.SetValue(strValue, intData);

                key1.Flush();

                key1.Close();

                flag1 = true;

            }

            return flag1;

        }

 

        public static bool SaveSettingString(RegistryKey hKey, string strPath, string strValue, string strData, SaveStringType sType)

        {

            bool flag1=false;

            if (!RegistryHelper.IsKey(hKey, strPath))

            {

                RegistryHelper.CreateKey(hKey, RegistryHelper.PathOnly(strPath), RegistryHelper.FileOnly(strPath));

            }

//        'If it's the Default value and strData is "" then fill it in with "(value not set)"

            if ((strValue.Length == 0) & (strData.Length == 0))

            {

                strData = "(value not set)";

            }

            if (sType != SaveStringType.REG_SZ)

            {

                int num1=0;

                 int num2=0;

                if (hKey == Registry.ClassesRoot)

                {

                    num1 = -2147483648;

                }

                else if (hKey == Registry.CurrentUser)

                {

                    num1 = -2147483647;

                }

                else if (hKey == Registry.LocalMachine)

                {

                    num1 = -2147483646;

                }

                else if (hKey == Registry.Users)

                {

                    num1 = -2147483645;

                }

                else if (hKey == Registry.CurrentConfig)

                {

                    num1 = -2147483643;

                }

                else if (hKey == Registry.DynData)

                {

                    num1 = -2147483642;

                }

                else if (hKey == Registry.PerformanceData)

                {

                    num1 = -2147483644;

                }

                int num3 = RegistryHelper.RegCreateKey(num1, ref strPath, ref num2);

                num3 = RegistryHelper.RegSetValueEx(num2, ref strValue, 0, (int) sType, ref strData, strData.Length);

                num3 = RegistryHelper.RegCloseKey(num2);

                return flag1;

            }

            RegistryKey key1 = hKey.OpenSubKey(strPath, true);

            if (key1 != null)

            {

                key1.SetValue(strValue, strData);

                key1.Flush();

                key1.Close();

                flag1 = true;

            }

            return flag1;

        }

 

        public static string ShellFile(string path, string arguments, ProcessWindowStyle style)

        {

            string text1="";

            Process process1 = new Process();

            try

            {

                process1.StartInfo.FileName = path;

                process1.StartInfo.UseShellExecute = false;

                process1 = Process.Start(path, arguments);

                process1.WaitForExit();

            }

            finally

            {

                process1.Dispose();

            }

            return text1;

        }

 

 

        // Nested Types

        public enum SaveStringType

        {

            // Fields

            REG_EXPAND_SZ = 2,

            REG_MULTI_SZ = 7,

            REG_SZ = 1

        }

            #region  "Helper methods"

           

//          ' Append a backslash (or any character) at the end of a path

//          ' if it isn't there already

//          'http://66.102.7.104/search?q=cache:jfWf2rcyyTgJ:www.devx.com/vb2themax/Tip/18940+AddBackSlash&hl=en

            public static string AddBackslash(string Path, [Optional] string ch /* = @"\" */)

            {

                  if (StringType.StrCmp(Strings.Right(Path, 1), ch, false) != 0)

                  {

                        return (Path + ch);

                  }

                  return Path;

            }

//          'http://66.102.7.104/search?q=cache:m8ISK7XP3OoJ:vbboshi.diy.myrice.com/preblem/41-60/pr59.htm+RemoveBackSlash&hl=en

//          'aLSO http://relib.com/forums/thread847374.aspx

            public static string RemoveBackslash(string s)

            {

                  string text1="";

                  int num1 = Strings.Len(s);

                  if (num1 != 0)

                  {

                        if (StringType.StrCmp(Strings.Right(s, 1), @"\", false) == 0)

                        {

                              text1 = Strings.Left(s, num1 - 1);

                              goto Label_003A;

                        }

                        return s;

                  }

                  text1 = "";

                  Label_003A:

                        return text1;

            }

            //          'http://vb2themax.com/ShowContent.aspx?ID=40fcf8bb-79a0-49e0-b930-422211907215

            //          ' this code assumes the following Imports statement

            //          '     Imports System.Text

            public static string GetShortFileName(string path)

            {

                  StringBuilder builder1 = new StringBuilder(0x400);

                  int num1 = RegistryHelper.GetShortPathName(ref path, builder1, builder1.Capacity);

                  return builder1.ToString(0, num1);

            }

 

            [DllImport("kernel32", EntryPoint="GetShortPathNameA", CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]

            private static extern int GetShortPathName([MarshalAs(UnmanagedType.VBByRefStr)] ref string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);

 

           

            public static void FileAppend(string path, string text)

            {

                  //object obj1;

                  StreamWriter writer1 = File.AppendText(path);

                  writer1.Write(text);

                  writer1.Close();

                  //return obj1;

            }

 

//          'http://translate.google.com/translate?hl=en&sl=de&u=http://www.internet-magazin.de/praxis/cm/page/page.php%3Ftable%3Dpg%26id%3D1690&prev=/search%3Fq%3DPathOnly%2BFileOnly%26start%3D10%26hl%3Den%26lr%3D%26sa%3DN

            public static string FileOnly(string P)

            {

                  int num1 = Strings.InStrRev(StringType.FromInteger(0), P, IntegerType.FromString(""), CompareMethod.Binary);

                  P = Strings.Mid(P, num1 + 1);

                  return P;

            }

            public static object PathComplete(string P)

            {

                  if (StringType.StrCmp(Strings.Right(P, 1), "", false) == 0)

                  {

                        P = P + "";

                  }

                  return P;

            }

 

            //'Also you extract the complete path from a listing structure, by using the InstrRev function. Only, separated in contrast to tap before, the file name. In connection with the procedure shown at the beginning completely PathComplete manufacture you so complete path names.

            public static string PathOnly(string P)

            {

                  int num1 = Strings.InStrRev(StringType.FromInteger(0), P, IntegerType.FromString(""), CompareMethod.Binary);

                  if (num1 == 0)

                  {

                        num1 = 1;

                  }

                  P = Strings.Left(P, num1 - 1);

                  if (Strings.Len(P) == 2)

                  {

                        P = StringType.FromObject(RegistryHelper.PathComplete(P));

                  }

                  return P;

            }

            #endregion  //"Helper methods"

 

 

      }

}

 

 

Posted on Friday, September 30, 2005 3:14 PM None | Back to top


Comments on this post: Export Registry in C#

# re: Export Registry in C#
Requesting Gravatar...
Thank You, Thank You, Thank You!!!!

I've spent over 10 hours trying to do very simple API calls in VB.NET (yes, I realize your post was about c#). I just want to say how great that controlled insanity library was/is. Its awesome that you mentioned it and ported it to c#. The controlled insanity website was down when I was reading your post but I was able to see google's cache of the forum post. If it wasn't for you blogging about this I'd probably have spent another 10 fruitless hours Changing my P/Invoke Declares and and DllImport<> statements. One wrong thing and the whole API statment fails.

I know I'm not commenting on your code very specifically but I wanted to post anyway.

If anyone is googling about this or if you're really interested I had trouble declaring and using these API calls with P/Invoke:

RegOpenKeyA , RegOpenKey , RegQueryValueEx, and lastly RegSetValueEx.

That vb.net module provides functions called SaveSettingString and GetSettingString that showed me great examples.


-greg
Left by greg on Apr 07, 2006 3:50 PM

# re: Export Registry in C#
Requesting Gravatar...
It compiles fine but how do I rename a key.

RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\WebBrowser", true);
string value1 = listBox1.SelectedItem.ToString();
RegistryHelper.RenameValue(key, "\\", value1, textBox1.Text.ToString());

This just deletes the key.

Matt
Left by Matt on Sep 15, 2006 8:14 AM

# re: Export Registry in C#
Requesting Gravatar...
Matt,
I haven't tested the code, just converted from VB.
You should debug RenameValue, probably GetValueType returns unexpected value.
Let me know, if you find the fix.
Left by Michael Freidgeim on Sep 15, 2006 8:17 AM

# re: Export Registry in C#
Requesting Gravatar...
Hi,
Thanks a lot for the excellent article you wrote. In my application, I want to export the speech registry files on to my machine. I added your class to my application. the registry file is located in "HKEY_CURRENT_USER\Software\Microsoft\Speech\RecoProfiles\Tokens\". Whwn I tried to use the "GetAllKeys" method, hKey.OpenSubKey(strPath, true) returns always null value. So here What value I have to pass for strPath string? It complies without errors. Please help me regardig issue...

Thanks in advance..
Richard
Left by Richard on Dec 05, 2008 2:53 AM

# re: Export Registry in C#
Requesting Gravatar...
Hi,
In your article, in the method, ExportKey(string sRegKeyPath, string sfile), What value I have to pass for string sfile?
Left by Richard on Dec 05, 2008 3:10 AM

# re: Export Registry in C#
Requesting Gravatar...
Richard,
In the ExportKey(string sRegKeyPath, string sfile),
sfile is the path of hte file where you want to store the exported key.
Note, that in C# \ is a special escape charater, and you should use "\\" inside double quotes, or use @,
e.g. @"HKEY_CURRENT_USER\Software\Microsoft\Speech\RecoProfiles\Tokens\". May be it will help.
Left by Michael Freidgeim on Dec 05, 2008 11:56 AM

# re: Export Registry in C#
Requesting Gravatar...
If you cut out all the unnecessary code, and tidy up a little, your left with this;


public void ExportKey(RegistryKey RegKey, string SavePath)
{
var path = "\"" + SavePath + "\"";
var key = "\"" + RegKey.Name + "\"";

ShellFile("/e " + path + " " + key + "");
}

public void ShellFile(string arguments)
{
var process1 = new Process();
try
{
process1.StartInfo.FileName = "regedit.exe";
process1.StartInfo.UseShellExecute = false;
process1 = Process.Start("regedit.exe", arguments);
process1.WaitForExit();
}
finally
{
process1.Dispose();
}
}
Left by Jonathan Preece on Feb 19, 2010 7:47 AM

# re: Export Registry in C#
Requesting Gravatar...
How about using RegSaveKeyEx?
Left by John Williams on Mar 12, 2010 3:30 AM

# re: Export Registry in C#
Requesting Gravatar...
Испорчен Файл: C:/Windows/RegBack/ERDNT.INF
Left by Анатолий on Jul 23, 2010 2:09 PM

# re: Export Registry in C#
Requesting Gravatar...
No matter your windows system is XP or Vista, the easiest way to speed up your PC is have a tuneup360 in it; you can try the software "tuneup360". My friends and I all use it, it's seems really useful.
Left by jolin on Jan 10, 2011 1:49 AM

Your comment:
 (will show your gravatar)


Copyright © Michael Freidgeim | Powered by: GeeksWithBlogs.net