Collect system info for your application's runtime environment

Often your code gets run on a machine far away and it’s useful to gather some information about that machine automatically, perhaps for error reporting or statistics gathering.

This information could include the Operating System version, how much memory, logged in user, etc.

 

There are various means of gathering such information. Rather than using lots of APIs and rolling my own, I found SystemInfo.exe on my system and MSDN

 

SystemInfo is a console application which outputs to the console. To capture that data, we merely need to redirect the console StandardOuput

 

Also note that both C# and VB samples use both Method and Linq query syntax for sorting output.

 

Start VS2010. File->New->Project->VB or C# WPF Application.

 

Replace MainWindow.Xaml.VB/CS with the code below.

Of course, you can modify the GetInfo method to gather more info like free disk space, etc.

I’ve gathered more info by enumerating the running processes. From it, you can see the start time of your process, for example.

 

To get process information: a 32 bit process can’t get much information from a 64 bit process: An exception is thrown: “A 32 bit processes cannot access modules of a 64 bit process.”,

so build your app to run on a 64 bit OS.

 

To run on a 64 bit machine:

VB: Project->Properties->Compiler->AdvancedCompile options->TargetCPU->Any CPU

C#: Project->Properties->Build->Platform target: Any CPU

 

 

SystemInfo gives:

 

 

Systeminfo:

Host Name: CALVINH9

OS Name: Microsoft Windows 7 Enterprise

OS Version: 6.1.7601 Service Pack 1, v.178 Build 7601

OS Manufacturer: Microsoft Corporation

OS Configuration: Member Workstation

OS Build Type: Multiprocessor Free

Registered Owner: admin

Registered Organization: Microsoft IT

Product ID: 00392-918-5000002-85687

Original Install Date: 2/3/2010, 1:08:28 PM

System Boot Time: 10/20/2010, 11:00:05 PM

System Manufacturer: Dell Inc.

System Model: Studio 1558

System Type: x64-based PC

Processor(s): 1 Processor(s) Installed.

                           [01]: Intel64 Family 6 Model 37 Stepping 2 GenuineIntel ~2400 Mhz

BIOS Version: Dell Inc. A02, 12/23/2009

Windows Directory: C:\Windows

System Directory: C:\Windows\system32

Boot Device: \Device\HarddiskVolume2

System Locale: en-us;English (United States)

Input Locale: en-us;English (United States)

Time Zone: (UTC-08:00) Pacific Time (US & Canada)

Total Physical Memory: 8,053 MB

Available Physical Memory: 5,261 MB

Virtual Memory: Max Size: 16,103 MB

Virtual Memory: Available: 12,708 MB

Virtual Memory: In Use: 3,395 MB

Page File Location(s): D:\pagefile.sys

Domain: redmond.corp.microsoft.com

Logon Server: \\TK5-RED-DC-31

Hotfix(s): 5 Hotfix(s) Installed.

                           [01]: KB958559

                           [02]: KB2416754

                           [03]: KB958488

                           [04]: KB976902

                           [05]: KB976932

Network Card(s): 4 NIC(s) Installed.

                           [01]: Realtek RTL8168D/8111D Family PCI-E Gigabit Ethernet NIC (NDIS 6.20)

                                 Connection Name: Local Area Connection

                                 Status: Media disconnected

                           [02]: Dell Wireless 1520 Wireless-N WLAN Mini-Card

                                 Connection Name: Wireless Network Connection

                                 DHCP Enabled: Yes

                                 DHCP Server: 157.54.23.66

                                 IP address(es)

                                 [01]: 10.80.56.203

                                 [02]: fe80::2c5a:ec35:a53d:d23c

                                 [03]: 2001:4898:b8:2011:69fc:cc57:34f0:64d2

                                 [04]: 2001:4898:b8:2011:2c5a:ec35:a53d:d23c

                           [03]: Microsoft Virtual WiFi Miniport Adapter

                                 Connection Name: Wireless Network Connection 2

                                 Status: Media disconnected

                           [04]: Microsoft Loopback Adapter

                                 Connection Name: MS Loopback

                                 Status: Hardware not present

Env vars:

_NO_DEBUG_HEAP=1

_NT_SYMBOL_PATH=SRV*c:\symcache*\\ddrps\symbols;srv*c:\symcache*\\symbols\symbols

ALLUSERSPROFILE=C:\ProgramData

APPDATA=C:\Users\calvinh\AppData\Roaming

CommonProgramFiles=C:\Program Files (x86)\Common Files

CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files

CommonProgramW6432=C:\Program Files\Common Files

COMPUTERNAME=CALVINH9

ComSpec=C:\Windows\system32\cmd.exe

Copycmd=/y

COR_ENABLE_PROFILING=1

COR_PROFILER={01673DDC-46F5-454F-84BC-F2F34564C2AD}

COR_PROFILER_PATH=D:\MemSpect\Vsassert.dll

EMC_AUTOPLAY=C:\Program Files (x86)\Common Files\Roxio Shared\

FP_NO_HOST_CHECK=NO

HOMEDRIVE=C:

HOMEPATH=\Users\calvinh

INSTALL_TYPE=WDS-CLEAN

LOCALAPPDATA=C:\Users\calvinh\AppData\Local

LOGONSERVER=\\TK5-RED-DC-31

NUMBER_OF_PROCESSORS=4

OANOCACHE=1

OS=Windows_NT

Path=c:\bin;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\System Center Operations Manager 2007\;C:\Program Files (x86)\Common Files\Roxio Shared\10.0\DLLShared\;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files\Dell\Dell Wireless WLAN Card;C:\Program Files (x86)\Microsoft Application Virtualization Client;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\

PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

PROCESSOR_ARCHITECTURE=x86

PROCESSOR_ARCHITEW6432=AMD64

PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 37 Stepping 2, GenuineIntel

PROCESSOR_LEVEL=6

PROCESSOR_REVISION=2502

ProgramData=C:\ProgramData

ProgramFiles=C:\Program Files (x86)

ProgramFiles(x86)=C:\Program Files (x86)

ProgramW6432=C:\Program Files

PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\

PUBLIC=C:\Users\Public

RoxioCentral=C:\Program Files (x86)\Common Files\Roxio Shared\10.0\Roxio Central36\

SESSIONNAME=Console

SystemDrive=C:

SystemRoot=C:\Windows

TEMP=C:\Users\calvinh\AppData\Local\Temp

TMP=C:\Users\calvinh\AppData\Local\Temp

UATDATA=C:\Windows\SysWOW64\CCM\UATData\D9F8C395-CAB8-491d-B8AC-179A1FE1BE77

USERDNSDOMAIN=REDMOND.CORP.MICROSOFT.COM

USERDOMAIN=REDMOND

USERNAME=calvinh

USERPROFILE=C:\Users\calvinh

VS100COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\

windir=C:\Windows

 

 

 

<C# Code>

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

using System.IO;

namespace WpfApplication2

{

    /// <summary>

    /// Interaction logic for MainWindow.xaml

    /// </summary>

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

            this.Content = new TextBox()

            {

                Text = GetInfo(),

                HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,

                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,

                FontFamily = new FontFamily("Courier New")

            };

        }

        string GetInfo()

        {

            var sb = new System.Text.StringBuilder();

            var sysdir = System.Environment.GetEnvironmentVariable("systemroot");// c:\windows

            var systeminfoFile = System.IO.Path.Combine(sysdir, @"system32\systeminfo.exe");

            if (File.Exists(systeminfoFile))

            {

                var psinfo = new System.Diagnostics.ProcessStartInfo

                {

                    FileName = systeminfoFile,

                    UseShellExecute = false,

                    RedirectStandardOutput = true

                };

                var p = System.Diagnostics.Process.Start(psinfo);

                var sr = p.StandardOutput;

                sb.Append(sr.ReadToEnd());

            }

            sb.AppendLine();

            sb.AppendLine("Running Processes");

            foreach (System.Diagnostics.Process proc in

                System.Diagnostics.Process.GetProcesses().OrderBy(p=>p.ProcessName))

            {

                try

                {

                    sb.AppendLine(String.Format("{0,6} {1,-20} {2,12:n0} {3,4} {4,25} {5,-50} {6,-50}",

                                                proc.Id,

                                                proc.ProcessName,

                                                proc.WorkingSet64,

                                                proc.Threads.Count,

                                                proc.StartTime,

                                                proc.MainWindowTitle,

                                                proc.MainModule.FileName

                                                ));

                }

                catch (Exception ex)

                {

                    sb.AppendLine(proc.ProcessName + " " + ex.Message);

                }

            }

            sb.AppendLine();

            sb.AppendLine("Env vars:");

            foreach (string envvar in

                (from string env in System.Environment.GetEnvironmentVariables().Keys

                 orderby env

                 select env))

            {

                sb.AppendLine(envvar + "=" + System.Environment.GetEnvironmentVariable(envvar));

            }

            return sb.ToString();

        }

    }

}

 </C# Code>

 

<VB Code>

Class MainWindow

    Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

        Me.Content = New TextBox With {

            .Text = GetInfo(),

            .VerticalScrollBarVisibility = ScrollBarVisibility.Auto,

            .HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,

            .FontFamily = New FontFamily("Courier New")

        }

    End Sub

    Function GetInfo() As String

        Dim sb As New Text.StringBuilder

        Dim sysdir = System.Environment.GetEnvironmentVariable("systemroot") ' c:\windows

        Dim systeminfoFile = IO.Path.Combine(sysdir, "system32\systeminfo.exe")

        If IO.File.Exists(systeminfoFile) Then

            Dim psinfo = New ProcessStartInfo With {

                                  .FileName = systeminfoFile,

                                  .UseShellExecute = False,

                                  .RedirectStandardOutput = True

                              }

            Dim p = Process.Start(psinfo)

            Dim sr = p.StandardOutput

            sb.Append(sr.ReadToEnd)

        End If

        sb.AppendLine()

        sb.AppendLine("Running Processes")

        For Each proc In System.Diagnostics.Process.GetProcesses.OrderBy(Function(p As Process) p.ProcessName)

            Try

                sb.AppendLine(String.Format("{0,6} {1,-20} {2,12:n0} {3,4} {4,25} {5,-50} {6,-50}",

                                            proc.Id,

                                            proc.ProcessName,

                                            proc.WorkingSet64,

                                            proc.Threads.Count,

                                            proc.StartTime,

                                            proc.MainWindowTitle,

                                            proc.MainModule.FileName

                                            ))

            Catch ex As Exception

                sb.AppendLine(proc.ProcessName + " " + ex.Message)

            End Try

        Next

        sb.AppendLine()

        sb.AppendLine("Env vars:")

        For Each envvar As String In From env In System.Environment.GetEnvironmentVariables.Keys Order By env

            sb.AppendLine(envvar + "=" + System.Environment.GetEnvironmentVariable(envvar))

        Next

        Return sb.ToString

    End Function

End Class

 

</VB Code>