Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveDirectory: How to find if a domain is available?

Is there any way of finding out if a domain is available in ActiveDirectory before using GetDomain? I have an app where users should be able to add domains by themselves, and if they enter an invalid domain there should be an error. Right now it is handled by catching the exception below, but a user entering an invalid domain is hardly an exceptional happening, and the exception also can take a really long time to get thrown, especially if an ip adress is entered (it seems like). Is there a better solution to this?

public Domain RegisterUserDirectory(string domainId) {
  DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domainId);

  System.DirectoryServices.ActiveDirectory.Domain domain;
  try {
    domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(context);
  }
  catch (ActiveDirectoryNotFoundException adne) {
    // handle
  }
  catch (Exception e) {
    Log.Warning("Failed to contact domain {0}: {1}", domainId, e.Message);
    throw;
  }

  ...
  ...
}
like image 607
erik Avatar asked Dec 16 '22 18:12

erik


1 Answers

The only other option I can think of is using the forest to enumerate the domains. i.e.

 var myDomain = Domain.GetCurrentDomain();  //or .GetComputerDomain();
 var forestDomains = myDomain.Forest.Domains;

This assumes all the domains you want are in the same forest. You'd then need to test your user inputed domainId against this collection, probably testing against each domains .Name property.

like image 171
Grhm Avatar answered Jan 09 '23 00:01

Grhm