我只想感谢 Bryan Roach,我能够解决我的问题。我还意识到我可以将我的 C# 项目 Build 设置为 Platform Target x64 并避免错误,因为它会搜索 64 位注册表区域。但是,我觉得任何 CPU 和能够解决问题的程序本身更适合我的应用程序。
string ServerName = "REMOTE_COMPUTER";
PrincipalSearcher pSearch = new PrincipalSearcher();
pSearch.QueryFilter = new UserPrincipal(new PrincipalContext(ContextType.Machine, ServerName, null, ContextOptions.Negotiate));
try
{
foreach (UserPrincipal userUP in pSearch.FindAll())
{
//Missing Registry Keys will error on pSearch.FindAll();
//Either Build > Platform Target == x64 or deal with it.
}
}
catch(FileNotFoundException ex)
{
if(ex.Source.Equals("Active Directory") &&
ex.TargetSite.MemberType.ToString().Equals("Method") &&
ex.TargetSite.Name.Equals("GetInfo"))
{
//It's possible the registry keys haven't been moved to x86 location on a 64 bit machine:
//From: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion (64 bit)
//To: HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion (32 bit compatability area)
//String Properties need to be present: RegisteredOwner, RegisteredOrganization
try
{
Hack_Fixx64RegistryForGettingLocalAccounts(ServerName);
//Recall function or whatever to try again with fixed registry.
}
catch
{ }
}
}
然后对于将注册表项复制到正确位置的功能:
private void Hack_Fixx64RegistryForGettingLocalAccounts(string ServerName)
{
RegistryKey remoteKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, ServerName, RegistryView.Registry64);
if(remoteKey != null)
{
//Get keys stored on 64 bit location
RegistryKey x64regkey = remoteKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
string regOwner = Convert.ToString(x64regkey.GetValue("RegisteredOwner", ""));
string regOrganization = Convert.ToString(x64regkey.GetValue("RegisteredOrganization", ""));
//Add missing keys on 64 bit OS in correct location for 32 bit registry area. The Wow6432Node is for 32-bit apps that run on 64-bit window versions.
remoteKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, ServerName, RegistryView.Registry32);
if(remoteKey != null)
{
RegistryKey x86regkey = remoteKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", true);
x86regkey.SetValue("RegisteredOwner", regOwner);
x86regkey.SetValue("RegisteredOrganization", regOrganization);
}
}
}