C# Tips & Tricks #32 -Ways to Get Computer Name

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();
        }

    }
}
Different Ways to get the computer name in c#

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...