In this article, you will learn how to find the hostname of the computer in C#. There are many ways to get the hostname of the local machine.
Here are some examples to get the hostname of the computer in C#.
In this example, we used the System.Environment.MachineName
to get the NetBIOS name of this local computer. The Environment class is inherited from the System.Object
. It provides information about the current platform and environment of the executable application.
Here is the source code of the program to find the hostname of the local machine in C#
using System;
namespace Tutorialsrack
{
class Program
{
/* How to Get the Computer Name in C# */
static void Main(string[] args)
{
Console.WriteLine("Host Name is: "+ Environment.MachineName);
//Hit ENTER to exit the program
Console.ReadKey();
}
}
}
In this example, we used HttpContext.Current.Server.MachineName
to get the HttpServerUtility object that provides methods used in processing Web requests. If you want to get the hostname using the web applications, then you used this to get the computer name in C#.
string HostName = System.Web.HttpContext.Current.Server.MachineName;
In this example, we used the Dns.GetHostName()
method to get the name of the local computer in C#. For using Dns.GetHostName()
method, first, you need to include the System.Net
namespace in your project.
Here is the source code of the program to find the hostname of the local machine in C#
using System;
using System.Net;
namespace Tutorialsrack
{
class Program
{
/* How to Get the Computer Name in C# */
static void Main(string[] args)
{
Console.WriteLine("Host Name is: "+ Dns.GetHostName());
//Hit ENTER to exit the program
Console.ReadKey();
}
}
}
In this example, we used the System.Environment.GetEnvironmentVariable()
to get the Local Machine Name or computer name in C#.
Here is the source code of the program to find the hostname of the local machine in C#
using System;
namespace Tutorialsrack
{
class Program
{
/* How to Get the Computer Name in C# */
static void Main(string[] args)
{
Console.WriteLine("Host Name is: "+ Environment.GetEnvironmentVariable("COMPUTERNAME"));
//Hit ENTER to exit the program
Console.ReadKey();
}
}
}
I hope this article will help you to understand how to find the local machine or computer name in c#.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments