10

I saved a byte array to registry using following code

Byte[] value = new byte[16]{
    0x4a,0x03,0x00,0x00, 
    0x45,0x02,0x00,0x00, 
    0xb7,0x00,0x00,0x00, 
    0x9d,0x00,0x00,0x00
};

RegistryKey key = Registry.CurrentUser.CreateSubKey(KeyName);
key.SetValue(@"Software\Software\Key", value, RegistryValueKind.Binary);

Here is the key created using above code:

[HKEY_CURRENT_USER\Software\Software\Key]  
    "LOC"=hex:4a,03,00,00,45,02,00,00,b7,00,00,00,9d,00,00,00

Now I want to read the same data back to byte array format. Following code can read the same data but the output is of type object.

RegistryKey key = Registry.CurrentUser.OpenSubKey(KeyName);
object obj =  key.GetValue(@"Software\Software\Key", value);

Here casting to byte[] does not work. I know I can use serializer or streams to achieve this task. I would like to know if there is an easier way to read data back to byte[] type (A two liner code)?

Please note this question is in C++

4
  • 1
    Cast should work. What error are you getting? Commented Jan 17, 2013 at 8:44
  • 2
    What is Value in your case? Just save the instance variable value as such and cast back. that should work.. Commented Jan 17, 2013 at 8:46
  • @nawfal, Thanks for your answer. It was my coding mistake. you cought my mistake. The object Value and value were different. That was the reason I was getting Invalid Cast error. I edited my question and I'm going to keep it for future reference. thanks again Commented Jan 17, 2013 at 9:29
  • Please don't edit the question. Add an answer. Commented Jan 17, 2013 at 10:40

2 Answers 2

11

To write a byte array to registry use following code

Byte[] value = new byte[]{
    0x4a,0x03,0x00,0x00, 
    0x45,0x02,0x00,0x00, 
    0xb7,0x00,0x00,0x00, 
    0x9d,0x00,0x00,0x00
};

RegistryKey key = Registry.CurrentUser.CreateSubKey(KeyName);
key.SetValue(@"Software\AppName\Key", value, RegistryValueKind.Binary);

To Retrieve the data back from registry into Byte[] format use following:

RegistryKey key = Registry.CurrentUser.OpenSubKey(KeyName);
byte[] Data =  (byte[]) key.GetValue(@"Software\AppName\Key", value);

Note: CurrentUser is name of the root for your Key location and points to HKEY_CURRENT_USER

Sign up to request clarification or add additional context in comments.

Comments

-1

I test in VB.NET:

Dim obj As Object = key.GetValue("Software\Software\Key", value__1)`
Dim v As [Byte]() = CType(obj, Byte())`

and it works

so in C# should be:

Byte[] v = Convert.ToByte(obj);

1 Comment

Thanks for your answer but Convert.ToByte returns a single byte

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.