I want to create a user with a program (C#, .net 4.5):
String Domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
...
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain))
{
if (UserPrincipal.FindByIdentity(pc, IdentityType.UserPrincipalName, USER) != null)
{
.. error message ..
...
At least, this works for Domains. But creating a local user (creating on a computer belonging to a domain or a stand alone computer) did not work (Executing user is am Administrator - manual adding a user works).
I've tried to set the Domain-Name to
- System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().HostName;
- "localhost"
- "127.0.0.1"
But then I got the following error message at FindByIdentity:
System.DirectoryServices.AccountManagement.PrincipalServerDownException:
Mit dem Server konnte keine Verbindung hergestellt werden. --->
System.DirectoryServices.Protocols.LdapException: Der LDAP-Server ist nicht verfügbar.
(German, I added line breaks) Roughly translated: "Could not connect to Server -> LDAP server is not accessible."
I also changed PrincipalContext to
using (PrincipalContext pc = new PrincipalContext(ContextType.Machine, Domain))
(and tested all domains as above). Then I got the following error message at FindByIdentity:
System.IO.FileNotFoundException: Der Netzwerkpfad wurde nicht gefunden.
(German) Roughly translated: "Network path not found".
(All tested at Windows 10 (in a domain) and a "clean" domain-less Windows 7.)
What can I do to make this working AND a just having one code path for all cases.
(Hint I also tested removing the domain name from PrincipalContext and adding it to the user "@" + Domain.)
Edit
using (PrincipalContext pc = new PrincipalContext(ContextType.Machine))
{
if (UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, USER) != null)
{
.. error message ..
...
works for local access on a non domain machine.