简体   繁体   中英

How to add new string to Registry Entry of type REG_MULTI_SZ?

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 class RegistryKey . 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#.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM