views:

999

answers:

5

How do I detect if my program runs in an Active Directory environment?

I'm using C# and .Net 2.0

+3  A: 

One way might be to query the LOGONSERVER environmental variable. That'll give the server name of your AD controller... Which, as far as I know, will be blank (or match current workstation? Not sure) if it isn't currently logged into a domain.

Example Usage:

string ADServer = Environment.GetEnvironmentVariable("LOGONSERVER");
Kevin Fairchild
+3  A: 

Try getting Environment.UserDomainName and comparing it to Environment.MachineName. If the two are the same then it's likely that the user does not have a domain. If they are not the same then the user is logged into a domain which must have a directory server.

Captain Toad
A: 

From http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.path.aspx

To bind to the current domain using LDAP, use the path "LDAP://RootDSE", then get the default naming context and rebind the entry.

So without a domain the binding to "LDAP://RootDSE" should either fail or return nothing. I didn't try it for myself.

use System.DirectoryServices; // add reference to system.directoryservices.dll

...

DirectoryEntry ent = new DirectoryEntry("LDAP://RootDSE");
String str = ent.Properties["defaultNamingContext"][0];
DirectoryEntry domain = new DirectoryEntry("LDAP://" + str);

This is definitely a cleaner way of checking for an Active Directory than relying on an environment variable (which the user could delete or add to spoof the program).

VVS
+2  A: 

This code will check if the Computer itself is a member of a domain

using System.DirectoryServices.ActiveDirectory;


bool isDomain = false;

try
{
    Domain.GetComputerDomain();
    isDomain = true;
}
catch (ActiveDirectoryObjectNotFoundException)
{
}

However the computer can be in a domain, but the currently logged in user may be a local user account. If you want to check for this use the Domain.GetCurrentDomain() function

Ollie
I get false when I'm logged with a local user, true when logged with a domain user...
vIceBerg
What about an NT4 domain without an active directory?
VVS
+1  A: 

I found something that works:

using System.Net.NetworkInformation;

IPGlobalProperties.GetIPGlobalProperties().DomainName;

Works with a local user and a domain user.

vIceBerg