c sharp

C# Environment.UserName Property

If you want to get the username of the system/machine using C#, the UserName property is used.
Environment Class in C# provides information about the working environment like variables, methods used, and system related information. It is possible to get the platform ID’s, Domain names, and check the modifiers present in C# application.Environment Class has vast range of applications in C# and .NET. It mainly tells us the system information without checking manually.

Environment.UserName

UserName Property in Environment class returns the current username. It will fetch the user present in the current thread in C# or ASP.NET Application.

If you are running your C# application on Windows Operating system, UserName Property fetches the Usernme with respect to GetUserName function in Windows.

If you are running your C# application on Linux or Unix Operating system, UserName Property fetches the Usernme with respect to getpwuid_r function in Linux/Unix OS.

Syntax:

string Environment.UserName

 
Return Type:

String

Example 1:

Here, we will return the UserName.

using System;
class Linuxhint
{
    //let's implement the UserName property inside main method
    static public  void Main()
    {
        //get the user name
        Console.WriteLine("The User is: "+Environment.UserName);
    }
}

 
Output:


We can see that the name of the user is “Chandu”.

Explanation:

Line 5:

We are implementing our property inside the Main method.

Line 8:

Console.WriteLine("The User is: "+Environment.UserName);

 
Here we are directly using the UserName property to return the name of the user

Example 2:

Here, we will return the username by storing it in a string variable.

using System;
class Linuxhint
{
    //let's implement the UserName property inside main method
    static public  void Main()
    {
         //get the user name
        string my_name=Environment.UserName;
        Console.WriteLine("The User is: "+my_name);

    }
}

 
Output:

Explanation:

Line 8:

string my_name=Environment.UserName;

 
Here, we are storing the username inside the string variable – my_name.

Line 9:

Console.WriteLine("The User is: "+my_name);

 
Finally, we are displaying the username using the Console.WriteLine() function.

Conclusion

By the end of this article, we came to know that the UserName property is used to return the name of the user in the current thread of an application that we are currently using. It returns the username in the form of a string. We discussed two examples by implementing this property in two ways.

About the author

Gottumukkala Sravan Kumar

B tech-hon's in Information Technology; Known programming languages - Python, R , PHP MySQL; Published 500+ articles on computer science domain