Writing MULTI_SZ to registry

B

Bry

Having mastered reading a multi_sz from the registry into an array
using:

// Max of 999 is fine in this instance
string[] myArray = new string[999];
myArray = (string[]) (myRegKey.GetValue("RegValue"));
// myArray will now contain a small number of elements with data in
them

I'm trying to do the opposite and write it back to the registry using:

// I may have added a few elements to the array since
// it was loaded from the registry in the above example.
myRegKey.SetValue("RegValue", myArray, RegistryValueKind.MultiString);

but the last line gives a "RegistryKey.SetValue does not allow a
String[] that contains a null String reference." exception at run time.

The exception occurs because only the first few elements of the array
contain real data, the exception is thrown because the other elements
all contain 'null'.

How can I write only the used elements to the multi_sz registry value?
Note that the array will never contain a fixed number of elements, but
the max of 999 will never be achieved (although I have allowed for this
occuring in my code).

Thanks.
 
B

Bry

I've found a way around this. My data type when loaded from the
registry is an array, but I now convert this to an arraylist which
allows better manipulation throughout my code. When I want to write the
data back to the registry I need to convert the arraylist back to a
fixed size array.

string[] myArray = new string[myArrayList.Count];
for (int loop = 0; loop < myArrayList.Count; loop++)
{
myArray[loop] = (string) myArrayList[loop];
}
regKey.SetValue("myMultiSZValue", myArray,
RegistryValueKind.MultiString);

I'm sure there is a much easier way to do this, but hopefully this
might help someone else with the same problem.
 
J

Joshua Mitts

Hi Bry,

Question: Do you know the # of real elements in the array? If so, you can
create a new array that contains only that # of elements and copy the
contents into this new array. If not, you can determine this amount with a
loop (i.e. loop until you reach null and count up with an accumulator), but
that slows down performance.

You can also try initializing your array to string.Empty, or replacing the
nulls with String.Empty, etc. But you need to evaluate if that's the
behavior you want or if the perf hit associated with doing that is
acceptable.
 
B

Bry

Thanks Joshua, that's kind of what I've done (you posted at the same
time as my previous message).

The string.empty idea is interesting, I might give that a go at a later
date. The arraylist conversion allows me much more control throughout
the rest of my code now, however I'm sure I can optimise the code that
performs the conversion a little better than my first attempt.

Thanks for your help.
Bry.
 

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