Different Ways to get the computer name in c#

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.

Different Ways to get the 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");


Different Ways to get the computer name in c#

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply