coding computer data depth of field

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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...