问题
I am really get stucked with something. I have a string which includes hex values:
string creatorSid = @"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";
I want to put that into the registrykey which requires binary values.
I tried this:
key.SetValue("creatorSID", creatorSid , RegistryValueKind.Binary);
But I got error message that it can not be converted.
Here is the complete Code so far:
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);
}
}
}
It`s writing the entry now, but the values are changed. If i check the key there is: "30 00 31 00 ....." in it. But it must be: "01 00 0c 80....." (must be exactly the value from the string)
回答1:
When you have string, you've to use RegistryValueKind.String
.
key.SetValue("creatorSID", creatorSid , RegistryValueKind.String);
If at all you need to use RegistryValueKind.Binary
, you need to convert the string
to byte[]
and store it as byte[]
.
To store the value:
var data = Encoding.Unicode.GetBytes(creatorSid);
key.SetValue("creatorSID", data, RegistryValueKind.Binary);
To get the value back:
var data = (byte[])key.GetValue("creatorSID");
if (data != null)
{
string creatorSID = Encoding.Unicode.GetString(data);
}
RegistryKey.SetValue
Edit: It seems you don't need to convert the ,
character as byte. Try the following.
To store the value:
var data = security.Split(',')
.Select(x => Convert.ToByte(x, 16))
.ToArray();
key.SetValue("creatorSID", data, RegistryValueKind.Binary);
To get the value back:
var data = (byte[])key.GetValue("creatorSID");
if (data != null)
{
string creatorSID = string.Join(",", data.Select(x => x.ToString("x2")).ToArray());
}
来源:https://stackoverflow.com/questions/25301486/write-a-stringformated-hex-block-to-registry-in-binary-value