I am trying to use PrincipalContext to check if a local user group exists on a remote computer.
I am having problems with PrincipalContext
:
PrincipalContext ctx = new PrincipalContext(ContextType.Machine, machine, null, ContextOptions.Negotiate)
It works in such scenarios:
However it doesn't work in opposite direction:
I am getting these errors:
Unhandled Exception: System.IO.FileNotFoundException: The network path was not found.
Unhandled Exception: System.Runtime.InteropServices.COMException: The network path was not found.
The first exception is for virtual machine, second for workgroup machine.
All machines have user with the same name and password and the code was executed from that user.
How to solve this issue?
I found the answer. It looks that DirectoryServices doesn't work on remote Windows 7 or newer. I guess when a computer is in a workgroup then it is local and we can connect and when it is in a domain then it is remote.
I followed steps described here:
System.IO.FileNotFoundException: The network path was not found. Exception while using DirectoryEntry object on windows 7
and here:
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
However I can't change services and registry settings on production servers. I found such way to get group:
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>();