Writing values to the registry with C#

13,421

Solution 1

I'm guessing you just need to find the right class to use to write to the registry. Using this class makes it relatively simple. Is this all you're looking for?

string key = @"HKEY_CLASSES_ROOT\.sgdk2";
string valueName = string.Empty; // "(Default)" value
string value = "sgdk2file";

Microsoft.Win32.Registry.SetValue(key,valueName, value,
   Microsoft.Win32.RegistryValueKind.String);

To convert a hex string into binary data:

static byte[] HexToBin(string hex)
{
   var result = new byte[hex.Length/2];
   for (int i = 0; i < hex.Length; i += 2)
   {
      result[i / 2] = byte.Parse(hex.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
   }
   return result;
}

If you need to see these bytes as hexadecimal again, you can use code like this:

static string BytesToHex(byte[] bytes)
{
   System.Text.StringBuilder sb = new StringBuilder();
   for (int i = 0; i < bytes.Length; i++)
   {
      sb.Append(bytes[i].ToString("x2"));
   }
   return sb.ToString();
}

As this code demonstrates, the bytes represented as hex 0e, ff and 10 get converted to binary 00001110, 11111111 and 00010000 respectively.

static void Main(string[] args)
{
   byte[] bytes = HexToBin("0eff10");
   Console.WriteLine(BytesToBinaryString(bytes));
}

static byte[] HexToBin(string hex)
{
   var result = new byte[hex.Length / 2];
   for (int i = 0; i < hex.Length; i += 2)
   {
      result[i / 2] = byte.Parse(hex.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
   }
   return result;
}

static string BytesToBinaryString(byte[] bytes)
{
   var ba = new System.Collections.BitArray(bytes);
   System.Text.StringBuilder sb = new StringBuilder();
   for (int i = 0; i < ba.Length; i++)
   {
      int byteStart = (i / 8) * 8;
      int bit = 7 - i % 8;
      sb.Append(ba[byteStart + bit] ? '1' : '0');
      if (i % 8 == 7)
         sb.Append(' ');
   }
   return sb.ToString();
}

Solution 2

So you have a string that you need to convert to binary and write to the registry? Does this work?

string valueString = "this is my test string";
byte[] value = System.Text.Encoding.ASCII.GetBytes(valueString);
Microsoft.Win32.Registry.SetValue(keyName, valueName, valueString, Microsoft.Win32.RegistryValueKind.Binary);
Share:
13,421
manemawanna
Author by

manemawanna

I'm fairly new to the world of programming having only, done it in two modules of my degree course, which was focused more on Networks. However I now have a programming role to create internal applications and have a steep learning curve so I'm learning something new everyday hence some of the what might seem sillier questions. But I aspire to be better than I am and improve myself and my programming skills. Current languages worked with: VB6, C/C++, C# (Current language)

Updated on June 04, 2022

Comments

  • manemawanna
    manemawanna almost 2 years

    I'm in the process of creating a C# application which will monitor changes made to the registry and write them back to the registry next time the user logs on.

    So far I've got it monitoring changes, reporting them, writing the hive, key and value to a text file. I'm now at the point where I need to take them values out of the file and place them back into the registry. Now I've looked at various tutorials but none have been able to answer the question/problem I have, so for example the registry key I wish to change is:

    HKEY_USERS\S-1-5-21-2055990625-1247778217-514451997-41655\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook\0a0d020000000000c000000000000046 the value of 01020402 and the contents contained within that

    What I want to be able to do is write back to that and change the value as appropriate. I currently have 3 strings, one contains the key location, one the value and the final is the contents of the value, although I could easily change the string manipulation to get and not get whatever I need or don't need. So if someone could provide me with a way to write to that it would be appreciated.

    P.S so you know, that paticular value is a binary value that I converted to string for storage. If you require any further information please let me know.

    Any help would be appreciated....thanks

    EDIT Code I'm currently using:

    public class reg
    {
        public void write(string key, string valueName, string value)
        {
            Byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(value);
    
            Registry.SetValue(key, valueName, value, RegistryValueKind.Binary);
        }
    }
    
  • manemawanna
    manemawanna over 14 years
    Pretty much; the only issue I have is that the value is currently a string and when I try and write it as Binary which is what that key is, it does nothing, which is the main issue I'm having but the rest is perfect. That key I'm using is just a test key to make sure the system works, it changes or registers the change between a user selecting to have there outlook preview pane to the right or bottom of the screen.
  • manemawanna
    manemawanna over 14 years
    I've edited my question to include it. I think the main issue I have is that I should be saving the value in its original binary or hex format rather than text. But that was also something I had an issue with, as the byte array it returns in that code is not what I'd expect or correct.
  • manemawanna
    manemawanna over 14 years
    Just thought I'd give you an idea of what the key that I'm monitoring for now is, its a binary key which for example right now has a value of: 01 00 00 00 0e 02 00 00 3b 01 00 00 8a 02 f4 01 50 00 00 00
  • Bobby Adams
    Bobby Adams over 14 years
    Looks like you need to pass byteValue instead of value as the parameter.
  • manemawanna
    manemawanna over 14 years
    Sorry that was me playing about, as byteValue doesn't equal what I would like it to equal, so I didn't use it. Think I'll have to make a new question as this is going a bit off tangent now as really I need to know how to convert a string that represents a hex or binary value into a hex or binary value which is the same. So for example if I have a string containing 1110 I would like to convert that to a binary value which is also 1110 or if I have a hex 0e I would like to convert that into a hex value 0e.
  • Bobby Adams
    Bobby Adams over 14 years
    I added a code sample for converting hex to binary. If you have another question out there, let me know and I can post the same answer there.
  • manemawanna
    manemawanna over 14 years
    The codes spot on but it converts to a decimal value rather than binary, any ideas? I've had a little play around but nothing yet.
  • Bobby Adams
    Bobby Adams over 14 years
    What makes you think that a byte array represents decimal values? I think maybe you do not understand the nature of decimal and hexadecimal numbers. Decimal and hexadecimal are simply way of representing numeric values as a series of characters. A byte with its maximum numeric value can be represented in decimal as 255, or in hexadecimal as FF. If you have bytes of data, they are binary and do not correspond to decimal or hexadecimal representation unless they represent characters that in turn represent another number. (For example a byte for "3" and a byte for "7" could be decimal 37.)
  • Bobby Adams
    Bobby Adams over 14 years
    I added code for converting the binary values back to hexadecimal representation. Is that what you're looking for?
  • manemawanna
    manemawanna over 14 years
    I know how byte's work and the conversions that take place between dec, bin, oct and hex. I also understand that the conversion the code provided makes is a hex number to its dec representation in the byte array and it does that fine. But what I need is the Binary representation so if one of the hex values is 0e I need the byte hold 1110 as when I try and write it to the registry I will be writing it in a Binary format. Not sure if its something not working in another area of my program though. So I've accepted your answer the help has been really appreciated.
  • Bobby Adams
    Bobby Adams over 14 years
    I've added code demonstrating that 0e does get converted to 00001110.