While C#'s PerformanceCounter
class offers system performance data, directly obtaining total RAM isn't intuitive. A more efficient approach leverages the Microsoft.VisualBasic
assembly.
Employing the Microsoft.VisualBasic Assembly
Add a reference to the Microsoft.VisualBasic
assembly to your project. This grants access to the ComputerInfo
class:
<code class="language-csharp">using Microsoft.VisualBasic.Devices; ComputerInfo computerInfo = new ComputerInfo();</code>
Retrieving and Converting RAM Data
The ComputerInfo
class exposes the TotalPhysicalMemory
property, returning the total physical RAM in bytes:
<code class="language-csharp">long totalRAMBytes = computerInfo.TotalPhysicalMemory;</code>
For easier readability, convert bytes to megabytes (MB) or gigabytes (GB):
<code class="language-csharp">double totalRAMMB = totalRAMBytes / (1024.0 * 1024.0); double totalRAMGB = totalRAMMB / 1024.0;</code>
This concise code provides a straightforward method for determining total system RAM within a C# application.
The above is the detailed content of How Can I Get Total RAM in C#?. For more information, please follow other related articles on the PHP Chinese website!