06 May 2015

…fix your parameter: because “The parameter is incorrect.” when updating registry key

Problem
The parameter is incorrect.
    at Microsoft.Win32.RegistryKey.Win32Error(Int32 errorCode, String str)
    at Microsoft.Win32.RegistryKey.CreateSubKeyInternal(String subkey, RegistryKeyPermissionCheck permissionCheck, Object registrySecurityObj, RegistryOptions registryOptions)
    at Microsoft.Win32.RegistryKey.CreateSubKey

Solved
In my case user whose registry file I want to update (target user) is not logged in, therefore
..the user’s registry file is not loaded, therefore
…the registry path\key I’m pointing to is incorrect

My solution in a nutshell:
1.        Verify if the correct user id logged in (I could be lucky)

2.     Get the AccountID of current user logged in
      WindowsIdentity WId = WindowsIdentity.GetCurrent();
      WidAccountID = WId.User.ToString();

3.        Get the AccountID of the target user using NTAccount, SecurityIdentifier (see previous post)
      NTAccount NtAcct = new NTAccount(definedUserName);
      SecurityIdentifier SecId = SecurityIdentifier)NtAcct.Translate(typeof(SecurityIdentifier));
      SecAccountID = SecId.ToString();


4.        Compare the WidAccountID = SecAccountID
5.        If they are not equal, use RegLoadKey to load the target user’s registry hive file
6.        For above step, remember to prefix the registry sub key with registry hive alias

7.        If I’m lucky and target user is logged in, prefix registry sub key with AccountID

8.        Update the registry file
9.        Always close the registry key
10.     And if registry hive file was loaded, use RegUnLoadKey to unload

NOTE: I had a case where target user is not logged in but the hive file is loaded in registry, so my 3 checks are as follows:

1.   Target user logged in (WidAccountID = SecAccountID).
-        Set SecAccountID as registry path prefix.

2.   Target user not logged in but hive file loaded in registry. 
-        Set SecAccountID as registry path prefix.

3.   Target user not logged in, hive file not loaded in registry.
-        Load hive file and set hive alias as registry path prefix


This RegLoad help and many other sources tell you how to RegLoadKey and RegUnLoadKey