使用C#将值写入注册表

man*_*nna 2 c# registry windows-services

我正在创建一个C#应用程序,它将监视对注册表所做的更改,并在用户登录时将它们写回注册表.

到目前为止,我已经监控变化,报告它们,将hive,key和value写入文本文件.我现在正处于需要从文件中取出值并将它们放回注册表的位置.现在我看了各种教程,但没有一个能够回答我的问题/问题,所以例如我希望改变的注册表项是:

HKEY_USERS\S-1-5-21-2055990625-1247778217-514451997-41655\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook\0a0d020000000000c000000000000046 01020402的值及其中包含的内容

我想要做的就是回写它并根据需要更改值.我目前有3个字符串,一个包含键位置,一个包含值,最后一个是值的内容,尽管我可以轻松地更改字符串操作以获取而不是获取我需要或不需要的任何内容.因此,如果有人能为我提供一种写作的方式,那将是值得赞赏的.

PS所以你知道,那个特定值是一个二进制值,我转换为字符串进行存储.如果您需要任何进一步的信息,请告诉我.

任何帮助将不胜感激....谢谢

我正在使用的编辑代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Blu*_*kMN 6

我猜你只需要找到用于写入注册表的正确类.使用这个类使它相对简单.这就是你要找的全部吗?

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);
Run Code Online (Sandbox Code Playgroud)

要将十六进制字符串转换为二进制数据:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果您需要再次将这些字节视为十六进制,则可以使用以下代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

如此代码所示,表示为hex 0e,ff和10的字节分别转换为二进制00001110,1111111和00010000.

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();
}
Run Code Online (Sandbox Code Playgroud)