Writing values to the registry with C#

后端 未结 2 1467
伪装坚强ぢ
伪装坚强ぢ 2021-01-22 09:27

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

相关标签:
2条回答
  • 2021-01-22 10:05

    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);
    
    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
提交回复
热议问题