How do I get the computer name in .NET c#
308
votes
Duplicate Question link
– Malachi
@Malachi, that question is about Windows services.
– Sam
@Sam a windows service is just a windows application that runs in the background, so really it's the same thing.
– Malachi
@Malachi, yeah, I know what you mean. However, the I think the references to the ASP.NET-specific and Winforms-specific ways of doing this in the answers to this question mightn't apply in that question.
– Sam
@Malachi, I think you've misunderstood what I meant about ASP.NET. I wasn't referring to an ASP.NET application getting its clients' computer names, although doing so (for the DNS name) is probably easy since the application would get the clients' IP addresses. I was referring to ASP.NET applications getting their host computers' names. See the highest-rated answer here for an example.
– Sam
12 Answers
431
votes
System.Environment.MachineName
from a console or WinForms app.HttpContext.Current.Server.MachineName
from a web appSystem.Net.Dns.GetHostName()
to get the FQDN
See How to find FQDN of local machine in C#/.NET ? if the last doesn't give you the FQDN and you need it.
See details about Difference between SystemInformation.ComputerName, Environment.MachineName, and Net.Dns.GetHostName
81
votes
29
votes
Some methods are given below to get machine name or computer name
Method 1:-
string MachineName1 = Environment.MachineName;
Method 2:-
string MachineName2 = System.Net.Dns.GetHostName();
Method 3:-
string MachineName3 = Request.ServerVariables["REMOTE_HOST"].ToString();
Method 4:-
string MachineName4 = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
For more see my blog
16
votes
Well there is one more way: Windows Management Instrumentation
using System.Management;
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT Name FROM Win32_ComputerSystem");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_ComputerSystem instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Name: {0}", queryObj["Name"]);
}
}
catch (ManagementException e)
{
// exception handling
}
16
votes
4
votes
4
votes
I set the .InnerHtml of a <p>
bracket for my web project to the user's computer name doing the following:
HTML:
<div class="col-md-4">
<h2>Your Computer Name Is</h2>
<p id="pcname" runat="server"></p>
<p>
<a class="btn btn-default" href="#">Learn more »</a>
</p>
</div>
C#:
using System;
using System.Web.UI;
namespace GetPCName {
public partial class _Default : Page {
protected void Page_Load(object sender, EventArgs e) {
pcname.InnerHtml = Environment.MachineName;
}
}
}
1
votes
1
votes