Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total installed system memory - cross-platform solution

Tags:

c#

.net

.net-core

I'm writing a C# program, and one of the requirements I must fulfill is determining the total installed system memory for determining values for a config file. This isn't an XY problem, this information is mandatory.

Before I made this cross-platform, I could use the ComputerInfo class in the Microsoft.VisualBasic.Devices namespace, but this is not available in .NET Core, so I cannot use it on a non-Windows platform. The System.Diagnostics.Process class provides information on the memory available to the current process, but this does not include the total physical RAM available on the machine.

Is there a cross-platform way of querying this, or do I have to resort to having the user input this information manually?

like image 361
Arcanox Avatar asked Dec 09 '17 23:12

Arcanox


1 Answers

Since .NET Core is a cross-platform framework, I suspect that developers are still figuring out how to implement a solid system capable of collecting hardware information from different operating system and from a wide variety of hardware products.

It seems that you are not the first person attempting to achieve this task: https://github.com/dotnet/corefx/issues/22660

I think that you have to accomplish this through a tricky (and probably underperforming) workaround. I propose you one: use Process.Start (from System.Diagnostics library) in order to execute OS-specific commands (based on the current application environment) that are capable of providing the information you are looking for.

For example, for Linux you could use one of the following commands (depending on the format you want your output to have):

dmidecode -t 17 | grep  Size:
awk '/MemTotal/ {print $2}' /proc/meminfo

for MacOS one of the following commands:

hwprefs memory_size
system_profiler SPHardwareDataType | grep "  Memory:"

and so on...

I know it's bad, but I think it's still better than forcing your users to manually enter the value.

like image 176
Tommaso Belluzzo Avatar answered Oct 17 '22 16:10

Tommaso Belluzzo