编辑其他用户的注册表项

如何更改或编辑当前用户以外的其他用户的注册表值? 我知道其他用户的凭据。

您可以模拟用户,然后更改当前上下文的注册表。 以下是C#和Impersonation的几个资源:

  • 使用C#进行Windows模拟
  • 来自C#的Windows模拟

你想做的是这样的事情(伪):

using(var impersonation = new Impersonate(username,password)) { ChangeRegistry(keys, values); } 

当模拟被处置时,您又回来使用正在运行的用户。 下面是一个 Impersonate类的示例实现 ,它实现了IDisposable,就像上面显示的伪示例一样 , 这是另一个例子 。

以下是有关如何更改注册表值的示例 :

 var registry = Registry.CurrentUser; var key = registry.OpenSubKey( @"HKEY_CURRENT_USER\Some\Path\That\You\Want\ToChange", true); key.SetValue(null, ""); Registry.CurrentUser.Flush(); 

更新

因此,访问HKCU需要做的是,您还必须加载用户配置文件。 这是通过调用另一个名为LoadUserProfile Win32方法来完成的。 这里有一个完整的例子 ,你可以使用,但我将在这里包含重要的部分。

首先,您需要包含这样的Win32方法:

 [DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern bool LoadUserProfile(IntPtr hToken, ref ProfileInfo lpProfileInfo); [DllImport("userenv.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Auto)] public static extern bool UnloadUserProfile(IntPtr hToken, IntPtr lpProfileInfo); 

在模拟使用块中,您需要执行以下操作:

 ProfileInfo profileInfo = new ProfileInfo(); profileInfo.dwSize = Marshal.SizeOf(profileInfo); profileInfo.lpUserName = userName; profileInfo.dwFlags = 1; Boolean loadSuccess = LoadUserProfile(tokenDuplicate, ref profileInfo); 

在此之后,您应该可以访问HKCU 。 完成后,需要使用UnloadUserProfile(tokenDuplicate, profileInfo.hProfile);卸载配置文件UnloadUserProfile(tokenDuplicate, profileInfo.hProfile);

你有两个选择。 如果您拥有Filip Ekberg的凭据,您可以冒充该用户; 要么

HKCU只是HKEY_USERS下其中一个键的象征性链接。 如果您知道该用户的SID,那么您可以在那里找到它。 您可以这样获得SID:

 var account = new NTAccount("userName"); var identifier = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier)); var sid = identifier.Value; 

更好的选择是冒充。 当您不知道该用户的凭据时,第二个选项可能会更好。 缺点是您需要管理权限才能写入别人的帐户。