How do I detect whether the machine is joined to an Active Directory domain (versus in Workgroup mode)?
ManagementObject cs;
using(cs = new ManagementObject("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'" ))
{
cs.Get();
Console.WriteLine("{0}",cs["domain"].ToString());
}
That should allow you to get the domain. I believe it will be null or empty if you are part of a workgroup and not a domain.
Make sure to reference System.Management
You can PInvoke to Win32 API's such as NetGetDcName which will return a null/empty string for a non domain-joined machine.
Even better is NetGetJoinInformation which will tell you explicitly if a machine is unjoined, in a workgroup or in a domain.
Edit: Using NetGetJoinInformation I just put together this, which worked for me:
public class Test
{
public static bool IsInDomain()
{
Win32.NetJoinStatus status = Win32.NetJoinStatus.NetSetupUnknownStatus;
IntPtr pDomain = IntPtr.Zero;
int result = Win32.NetGetJoinInformation(null, out pDomain, out status);
if (pDomain != IntPtr.Zero)
{
NetApiBufferFree(pDomain);
}
if (result == Win32.ErrorSuccess)
{
if (status == Win32.NetJoinStatus.NetSetupDomainName)
{
return true;
}
else
{
return false;
}
}
else
{
throw new Exception("Domain Info Get Failed");
}
}
}
internal class Win32
{
public const int ErrorSuccess = 0;
[DllImport("Netapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
public static extern int NetGetJoinInformation(string server, out IntPtr domain, out NetJoinStatus status);
[DllImport("Netapi32.dll")]
public static extern int NetApiBufferFree(IntPtr Buffer);
public enum NetJoinStatus
{
NetSetupUnknownStatus = 0,
NetSetupUnjoined,
NetSetupWorkgroupName,
NetSetupDomainName
}
}
The Environment variables could work for you.
Environment.UserDomainName
MSDN Link for some more details.
Environment.GetEnvironmentVariable("USERDNSDOMAIN")
I'm not sure this environment variable exists without being in a domain.
Correct me if I'm wrong Windows Admin geeks -- I believe a computer can be in several domains so it may be more important to know what domain, if any, you are in instead of it being in any domain.
Don't fool with pinvoke if you don't have to.
Reference System.DirectoryServices.Activedirectory, then call:
System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain()
Throws an ActiveDirectoryObjectNotFoundException if the machine is not domain-joined.
The Domain object that's returned contains the Name property you're looking for.