.Net 4.5 vs .Net 3.5 RegSetValueEx returning a bun

2019-09-09 21:52发布

问题:

I have recently ran into a problem with RegSetValueEx (from advapi32.dll). It looks like a REG_SZ saved with that method in .Net 3.5 gets incorrectly read in .Net 4.5 using RegistryKey.GetValue(). Illustration below:

//---.Net 3.5--- (no issues)
Call RegSetValueEx() to save base64 string value "ajG8s" to the registry
Call RegistryKey.GetValue() on that value returns "ajG8s"

//---.Net 4.5--- (no issues)
Call RegSetValueEx() to save base64 string value "ajG8s" to the registry
Call RegistryKey.GetValue() on that value returns "ajG8s"

//---.Net 3.5 & .Net 4.5--- (issues)
Call RegSetValueEx() to save base64 string value "ajG8s" to the registry (in .Net 3.5)
Call RegistryKey.GetValue() on that value returns "ajG8s\0\0\0\0\0\6\A\z./,'./Z?" (in .Net 4.5)

The code is 100% the same between the examples above - simply switching the .Net 4.5 version.

Originally I thought that maybe the string being written to the registry was not correctly null terminated - it is. I have also verified that this does not occur if I try to write the value using RegistryKey.SetValue() - only RegSetValueEx (from advapi32.dll) seems to cause this behaviour.

Now the simplest solution would be to simply search the returned string (in 4.5) for the first null terminating character and remove the rest of the string. That solution works, but I would rather figure out the root of the issue.

Any ideas on what is causing it? Many thanks!

回答1:

I've realized what the actual problem was. The actual issue was caused by our incorrect writing of the base64 string to the registry using WinApi RegSetValueEx() - the length property passed in was too high, and as a result and bunch of garbage was being written to the registry.

The actual problem was revealed because of (assumed) change in:

RegistryKey.GetValue()

between .Net 3.5 and 4.5. Where .Net 3.5 would terminate the GetValue() on the first '\0' character, the .Net 4.5 GetValue() would keep on reading until... some point.. That is why I was 'blaming' .Net - whereas it's our code that is to blame! Still - an interesting change to node.

Hopefully this helps somebody else with a similar problem :)