Read registry keys of type REG_MULTI_SZ into C# arrays

B

Bo

I am using RegistryKey.GetValue() method to retrieve values from
Windows Registry. I don't know how to read type REG_MULTI_SZ into a
string array. I have tried
string[] array = (string[]) RKey.GetValue(name);
But it gave me "Invalid Cast Exception".

Please provide C# sample code in your reply.

Thank you.
 
V

Vijaye Raji

Excerpt from MSDN:

Note When setting a value, the way in which the value being passed is
stored in the registry is interpreted. There is no way to control whether
the information being passed is stored as an sz, or an expanded_sz string,
and therefore, all string values are interpreted as standard sz values.
I guess if you extend this to read, you'll be able to read MULTI_SZ strings
as one string... although you should try a sample app to make sure.

-vJ
 
J

Jeffrey Tan[MSFT]

Hi Bo,

It should work, I do like this:
private void button1_Click(object sender, System.EventArgs e)
{
string[] before = new string[] {"Hello", "World"};
string[] after;
RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\GetValue");
key.SetValue("Test", before);
after = (string[])key.GetValue("Test");
foreach(string str in after)
{
MessageBox.Show(str);
}
key.Close();
}

And it works well.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
M

mikeb

Bo said:
I am using RegistryKey.GetValue() method to retrieve values from
Windows Registry. I don't know how to read type REG_MULTI_SZ into a
string array. I have tried
string[] array = (string[]) RKey.GetValue(name);
But it gave me "Invalid Cast Exception".

Something else is wrong - it works fine for me. I suspect that the value
being read by RKey.GetValue(name) is not really REG_MULTI_SZ.

I'll even post a complete example:

using System;
using Microsoft.Win32;

namespace MultiSZTest
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
string [] vals = (string [])
Registry.CurrentUser.GetValue( "test");
}
}
}

Note that I created a REG_MULTI_SZ registry value named "test" under
HKCU using RegEdit. Note that my test worked even if the value had no
data in it or just one string.

I also got no exception if the value "test" did not exist at all. In
that case, the vals array was null.

I did get the InvalidCastException (as expected) if "test" had a type of
REG_SZ.

Now you get to post a complete example that fails.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top