C#PrincipalContext找不到网络路径
-
22-12-2019 - |
题
我正在尝试使用PrincipalContext来检查远程计算机上是否存在本地用户组。
我有问题 PrincipalContext
:
PrincipalContext ctx = new PrincipalContext(ContextType.Machine, machine, null, ContextOptions.Negotiate)
它在这种情况下工作:
- 本地到本地机器
- 本地到虚拟机
- 域机器到工作组机器
然而,它不工作在相反的方向:
- 虚拟机到本地主机
- 工作组计算机到域计算机
我得到这些错误:
未处理的异常:System.IO.FileNotFoundException:未找到网络路径。
未处理的异常:系统。运行时。互操作服务。COMException异常:未找到网络路径。
第一个例外是虚拟机,第二个例外是工作组机器。
所有计算机都有具有相同名称和密码的用户,并且代码是从该用户执行的。
如何解决这个问题?
解决方案
我找到了答案。看起来DirectoryServices在远程Windows7或更高版本上不起作用。我猜当一台计算机在工作组中时,它是本地的,我们可以连接,当它在域中时,它是远程的。
我遵循这里描述的步骤:
System.IO.FileNotFoundException:未找到网络路径。在windows7上使用DirectoryEntry对象时出现异常
而在这里:
http://www.peppercrew.nl/index.php/2011/09/connect-to-remote-registry-fails-with-an-error-is-preventing-this-key-from-being-opened/
Enable File and Print sharing in the Firewall
Start the Remote Registry Service
Add remote user access to this registry entry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurePipeServers\winreg
但是,我无法更改生产服务器上的服务和注册表设置。我找到了这样的方式来获得组:
var server = new DirectoryEntry(string.Format("WinNT://{0},Computer", machine));
DirectoryEntry group = server.Children.Cast<DirectoryEntry>().Where(
d => d.SchemaClassName.Equals("Group") && d.Name.Equals("Administrators")
).Single<DirectoryEntry>();