在二进制值中将Stringformated Hex块写入注册表

时间:2014-08-14 06:32:44

标签: c# registry registrykey

我真的被某事搞定了。 我有一个包含十六进制值的字符串:

  

string creatorSid =   @" 01,05,00,00,00,00,00,05,15,00,00,00,10,b1,9d,4α,7α,85,7b,05,                                    79,05,b3,7c,EE,03,00,00&#34 ;;

我想把它放到需要二进制值的registrykey中。

我试过了:

  

key.SetValue(" creatorSID",creatorSid,RegistryValueKind.Binary);

但是我收到了无法转换的错误消息。

到目前为止,这是完整的代码:

class Program
{
    static void Main(string[] args)
    {
        String printerName = "Naked";
        RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Print\Printers\" + printerName , true);


        string security = "01,00,0c,80,d0,00,00,00,dc,00,00,00,00,00,00,00,14,00,00,00,02," +
                           "00,bc,00,07,00,00,00,00,00,24,00,0c,00,0f,00,01,05,00,00,00,00,00,05,15,00," +
                            "00,00,10,b1,9d,4a,7a,85,7b,05,79,05,b3,7c,ee,03,00,00,00,09,24,00,30,00,0f," +
                            "00,01,05,00,00,00,00,00,05,15,00,00,00,10,b1,9d,4a,7a,85,7b,05,79,05,b3,7c," +
                            "ee,03,00,00,00,09,14,00,00,00,00,10,01,01,00,00,00,00,00,03,00,00,00,00,00," +
                            "00,14,00,08,00,02,00,01,01,00,00,00,00,00,01,00,00,00,00,00,0a,14,00,00,00," +
                            "00,20,01,01,00,00,00,00,00,01,00,00,00,00,00,00,18,00,0c,00,0f,00,01,02,00," +
                            "00,00,00,00,05,20,00,00,00,20,02,00,00,00,0b,18,00,00,00,00,10,01,02,00,00," +
                            "00,00,00,05,20,00,00,00,20,02,00,00,01,01,00,00,00,00,00,05,12,00,00,00,01," +
                            "01,00,00,00,00,00,05,12,00,00,00";



        var data = Encoding.Unicode.GetBytes(security);

        try
        {
             key.SetValue("Security", data, RegistryValueKind.Binary);
        }
        catch (Exception exc)
        {

            Console.WriteLine(exc.Message);
            Console.WriteLine(exc.StackTrace);
        }



    }
}

它现在正在编写条目,但值已更改。如果我检查钥匙有:" 30 00 31 00 ....."在里面。但它必须是:" 01 00 0c 80 ....." (必须是字符串中的值)

1 个答案:

答案 0 :(得分:2)

如果您有字符串,则可以使用RegistryValueKind.String

key.SetValue("creatorSID", creatorSid , RegistryValueKind.String);

如果您需要使用RegistryValueKind.Binary,则需要将string转换为byte[]并将其存储为byte[]

存储值:

var data = Encoding.Unicode.GetBytes(creatorSid);
key.SetValue("creatorSID", data, RegistryValueKind.Binary);

要获得价值:

var data = (byte[])key.GetValue("creatorSID");
if (data != null)
{
    string creatorSID = Encoding.Unicode.GetString(data);
}

RegistryKey.SetValue

修改:您似乎不需要将,字符转换为字节。请尝试以下方法。

存储值:

var data = security.Split(',')
    .Select(x => Convert.ToByte(x, 16))
    .ToArray();
key.SetValue("creatorSID", data, RegistryValueKind.Binary);

要获得价值:

var data = (byte[])key.GetValue("creatorSID");
if (data != null)
{
    string creatorSID = string.Join(",", data.Select(x => x.ToString("x2")).ToArray());
}