Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment.MachineName equivalent for .NET Standard 1.4

I am creating a class library that will be used in a WPF project and a .NET Core project. I am trying to get the name of the machine using my application.

In both .NET Core and the WPF application I can use Environment.MachineName value. However in my .NET Standard Class library I cannot.

I get the following error:

'Environment' does not contain a definition for 'MachineName'

I tried doing what the answer suggested in this question but when I try to add System.Windows.Networking.Connectivity.NetworkInformation.GetHostNames() I get the following error:

The name 'Windows' does not exist in the current context

I assume that this only works for Windows 10 Universal Apps? Either way I would prefer a platform independent way of getting the machine name (this way seems like its meant for windows machines only)

like image 542
yitzih Avatar asked May 14 '17 08:05

yitzih


People also ask

How do I choose the target version of .NET standard library?

If you are not sure which version of . NET Standard you should target, go with 2.0 as it offers a balance of reach and APIs available for you to use. If your goal is to make your library usable for many frameworks as possible while gettings all the APIs you can from .

What is environment variable in .NET core?

Environment variable indicates the runtime environment in which an application is currently running. ASP.NET Core uses an environment variable called ASPNETCORE_ENVIRONMENT to indicate the runtime environment.

What is the difference between .NET Standard and .NET framework?

Net Standard is not a framework or platform of its own. It does not have implementations or a runtime, it just defines a specification what different . Net platforms has to implement to remain . Net Standard compliant.


1 Answers

Environment.MachineName is only available in .NET Standard > 1.5 using the System.Runtime.Extensions NuGet package (in .NET Standard 2.0 it is available automatically).

As an alternative, you can either use System.Net.Dns.GetHostName() by referencing the System.Net.NameResolution NuGet package or resolve the COMPUTERNAME (win) or HOSTNAME (*nix) environment variables via Environment.GetEnvironmentVariable("COMPUTERNAME").

like image 188
Martin Ullrich Avatar answered Oct 25 '22 01:10

Martin Ullrich