Alex
Alex

Reputation: 2609

Environment.UserDomainName equivalent in .NET Core console app

I need to determine the domain of the currently logged Windows user. I don't see Environment.UserDomainName in .NET Core neither I was able to find any alternative. Is it hidden elsewhere?

This is not duplicate of System.Environment in .NET Core question as I have no problem with getting Environment class in .NET Core. I need its particular property UserDomainName which is missing there.

Upvotes: 4

Views: 4717

Answers (1)

kimbaudi
kimbaudi

Reputation: 15615

Unfortunately, Environment.UserDomainName is not available for .NET Core.

However, .NET Core does provide Environment.GetEnvironmentVariable(), which allows you to access environment variables. Since USERDOMAIN environment variable is available for Windows and HOSTNAME environment variable is available for Linux and Mac, you can call Environment.GetEnvironmentVariable("USERDOMAIN") if its Windows, or Environment.GetEnvironmentVariable("HOSTNAME") if its Linux/Mac.

This class could be helpful:

public static class Machine 
{
    public static string User(){
        return Environment.GetEnvironmentVariable("USERNAME") ?? Environment.GetEnvironmentVariable("USER");
    }

    public static string Domain(){
        return Environment.GetEnvironmentVariable("USERDOMAIN") ?? Environment.GetEnvironmentVariable("HOSTNAME");
    }
}

Can get easily the username and domain: Machine.User(); or Machine.Domain();

Upvotes: 4

Related Questions