Subscribe to our YouTube Channel for more Videos

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");
            Console.WriteLine(method1);
            Console.WriteLine(method2);
            Console.WriteLine(method3);
            Console.ReadLine();
        }

    }
}

Different Ways to get the computer name in c#

Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.