How to get current Domain of the PC in C# and VB.NET

To get current Domain of the PC in C# and VB.NET you can use the snippet below.

Sample C#

using System;
using System.DirectoryServices.ActiveDirectory;

namespace de.Fesslersoft.DomainTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var myDomain = Domain.GetComputerDomain();
            foreach (DomainController dc in myDomain.DomainControllers)
            {
                Console.WriteLine("{0} - {1}", dc.IPAddress, dc.Name);
            }
            Console.Read();
        }
    }
}

Sample VB.NET

Imports System.DirectoryServices.ActiveDirectory

Namespace de.Fesslersoft.DomainTest
	Class Program
		Private Shared Sub Main(args As String())
			Dim myDomain = Domain.GetComputerDomain()
			For Each dc As DomainController In myDomain.DomainControllers
				Console.WriteLine("{0} - {1}", dc.IPAddress, dc.Name)
			Next
			Console.Read()
		End Sub
	End Class
End Namespace

Please rate this snippet

How to get the current username using C# or VB.NET

There is more than one way to get the current username using C# or VB.NET i will show you one using Environment Variable and one using the WindowsIdentity.

If you are in a Network the output of both methods is different.

 

using the Environment variable

 

Sample C#

string currUsername = Environment.UserName;

 

Sample VB.NET

Dim currUsername As String = Environment.UserName

using the WindowsIdentity

 

Sample C#

string currUsername = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

 

Sample VB.NET

Dim currUsername As String = System.Security.Principal.WindowsIdentity.GetCurrent().Name

 

Possible Output

Tip
if you want to use the Environment variables and want to get the Domainname also, take a look at Environment.UserDomainName Property

for more informations take a look at the MSDN: Environment.UserName, WindowsIdentity Class

Please rate this snippet