2

I am trying to get domain name using C# with the below code,

static void Main(string[] args)
{
    var domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName;
    Console.WriteLine(domainName);
    Console.ReadLine();
}

It prints domain name correctly in domain connected windows 8 machine. But it doesn't print anything in windows server 2012 R2 machine.

How to get domain name in Windows server 2012 machine.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Kumar
  • 3,782
  • 4
  • 39
  • 87

2 Answers2

1

I hope that works for you:

string domainName = System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name;
Orkun Bekar
  • 1,447
  • 1
  • 15
  • 36
1

In the past, I have used this code to get the domain name. It is accessed through the environmental variables on that machine.

string UserDomain = Environment.UserDomainName.ToString();
Console.WriteLine(UserDomain);

Perhaps the exception is caused from running it on a server for which the user does not have the appropriate permissions. Have you tried doing a "run As administrator" or "run as different user" with the exe?

Mark G
  • 557
  • 1
  • 6
  • 17
  • I have tried with Administrator too. But it is not working. I have tried to getting from environmental variable already. Its working. Is this a correct way to get the domain name? – Kumar May 09 '16 at 04:39
  • Kumar, A few more things to see if it leads you anywhere: 1) more specifically, have you opened a command prompt and run your exe from that command prompt? 2) I would try running the command "set" to see if returns all the environmental variables and see the values. 3) Check out the command iCacls. That might help figure what permissions that user has on that server. 4) I think the exception is pointing to some kind of permission/user issue. – Mark G May 09 '16 at 14:28
  • Works only when the current users accout is in same domain like the machine! – marsh-wiggle Dec 17 '20 at 20:53