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#.
Creating a string value is similar to creating a key – right-click on the key where you want to create the string value, hover on New in the menu, and then select String Value from the submenu.
Once you've located the registry key you want to add to, you can add the key or value you want to add: If you're creating a new registry key, right-click or tap-and-hold on the key it should exist under and choose New > Key. Name the new registry key and then press Enter.
Click Start, click Run, type regedit in the Open box, and then click OK. Locate and then click the subkey that holds the registry item or items that you want to change. Click File, and then click Export. This step backs up the subkey before you make any changes.
String Value: String Values are mostly human readable and only have a single line of textual information, like file paths. String Values are one of the most commonly used values in the Windows Registry. Binary Value: As the name implies, these values only contain binary data (0, 1).
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.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With