There are different ways in which the developers can get the computer name in their .NET application using C#.
- Using the MachineName property defined in the Environment class.
- Using the GetHostName method defined in the class System.Net.Dns.
- By passing the “COMPUTERNAME” string to the System.Environment.GetEnvironmentVariable method.
How to Get Computer Name in C#?
Below is a sample code demonstrating the retreival of the computer name using the above methods.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GinktageConsoleApps { class Program { static void Main(string[] args) { string method1 = Environment.MachineName; string method2 = System.Net.Dns.GetHostName(); string method3 = System.Environment.GetEnvironmentVariable("COMPUTERNAME"); Console.WriteLine(method1); Console.WriteLine(method2); Console.WriteLine(method3); Console.ReadLine(); } } }