Reputation: 1936
I have 1 registry entry of type REG_MULTI_SZ. This entry already contains some string in it.
Now i want to add 1 more string to it by using .net classRegistryKey
. this class has method key.SetValue(string,string)
. But when i use this method it removes all strings which are already there and then inserts new string, in short it overwrites.
I don't want to touch strings which are already there, just want to add new string at the end.
Anybody know how can we do this in C#.
Upvotes: 8
Views: 9311
Reputation: 61
As per Vinayak's answer above, if you want to append a value, you would need to read in the existing value and work with that.
So:
var registryValue = key.GetValue("KeyName");
to get the existing value, which should return a string array for a REG_MULTI_SZ. Then it's just a matter of appending the new value (or swapping out an existing value, if that takes your fancy). You can do this any way you prefer - create a List from the array and add a new value to it, create a new string array with a loop, make use of IEnumerable.Concat...
var stringList = new List<string>(registryValue as string[]);
stringList.Add("NewValue");
key.SetValue("KeyName", stringList.ToArray());
Obviously you'd want to put some defensive coding around this little sample - make sure you're actually getting back a string array, etc...
Upvotes: 6
Reputation: 1881
For a multi string value I would do this.
key.SetValue("MultipleStringValue", new string[] {"One", "Two", "Three"});
If it's a single value then as Wolfgang mentioned you should read existing and append.
Upvotes: 14
Reputation: 1685
There is no other way. You have to read the existing string first, then append your string to that and write the new concatenated string back.
Upvotes: 1