Writing values to the registry with C#

被刻印的时光 ゝ 提交于 2019-12-02 02:39:20

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();
}

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!