How to obtain operating system related information through C #, such as memory size, CPU size, machine name, environment variables and other operating system software, hardware related information

Source: Internet
Author: User
Tags osclass

This article through a demo, to explain how to obtain operating system related information through C #, such as memory size, CPU size, machine name, environment variables, such as operating system software, hardware-related information, only for learning to share the use, if there are deficiencies, please correct me.

knowledge points involved: Environment provides information about the current environment and platforms and how to manipulate them. ManagementClass represents the Common Information Model (CIM) management class. A management class is a WMI class, such as Win32_LogicalDisk and Win32_Process, which represents a disk drive, and the latter represents a process (such as a Notepad.exe). Members of this class can access WMI data using a specific WMI classpath.

Effect Chart

System Information: get information such as system directory, platform identification, login username, letter, domain, etc.

environment variable: that is, the operating system parameters to see if there is no immediate light for one of the information

Special directory: desktop, My Documents, favorites, etc. directory, is not very familiar with

operating system: The following is to obtain information on the CPU, such as model, name, number, speed, manufacturers and other information "can also get other such as memory, hard disk and other information"

The code is as follows:

namespace Demoenvironment {public partial class Mainfrom:form {public Mainfrom () {
        InitializeComponent (); } private void Mainfrom_load (object sender, EventArgs e) {string machinename = ENVIRONMENT.M
            Achinename;
            String osversionname = Getosversion (Environment.OSVersion.Version);
            string servicepack = Environment.OSVersion.ServicePack;
            Osversionname = Osversionname + "" + servicepack;
            string userName = Environment.username;
            string domainname = Environment.UserDomainName; String tickCount = (environment.tickcount/1000).
            ToString () + "s"; String systempagesize = (environment.systempagesize/1024).
            ToString () + "KB";
            string systemdir = Environment.systemdirectory;
            string stacktrace = Environment.stacktrace;
            String processorcounter = Environment.ProcessorCount.ToString (); String PLATFORM = Environment.OSVersion.Platform.ToString ();
            string newline = Environment.NewLine;
            bool Is64os = Environment.is64bitoperatingsystem;
            
            bool is64process = environment.is64bitprocess;
            string currdir = Environment.currentdirectory;
            string cmdline = Environment.commandline;
            string[] drives = Environment.getlogicaldrives ();
            Long WorkingSet = (environment.workingset/1024);
            This.lblMachineName.Text = machinename;
            This.lblOsVersion.Text = Osversionname;
            This.lblUserName.Text = UserName;
            This.lblDomineName.Text = domainname;
            This.lblStartTime.Text = TickCount;
            This.lblPageSize.Text = systempagesize;
            This.lblSystemDir.Text = Systemdir; This.lblLogical.Text = string.
            Join (",", drives);
            This.lblProcesserCounter.Text = Processorcounter;
           This.lblPlatform.Text = platform; This.lblNewLine.Text = Newline.tostring (); This.lblSystemType.Text = Is64os?
            "64bit": "32bit"; This.lblProcessType.Text = is64process?
            "64bit": "32bit";
            This.lblCurDir.Text = Currdir;
            This.lblCmdLine.Text = CmdLine; This.lblWorkSet.Text = Getphisicalmemory ().
            ToString () + "MB"; environment variable//HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment IDiction
            ary Dicmachine = Environment.getenvironmentvariables (environmentvariabletarget.machine); This.rtbVaribles.AppendText (String.
            Format ("{0}: {1}", "Machine environment variable", newline)); foreach (String str in Dicmachine.keys) {string val = Dicmachine[str].
                ToString (); This.rtbVaribles.AppendText (String.
            Format ("{0}: {1}{2}", str, Val, newline)); } this.rtbVaribles.AppendText (String. Format ("{0}{1}", ">>>>>>>>>>>>>>>>≫>>>>>>>>>>>>>>>>>>>>>>>>>>
            >>>>>>>>>>>>> ", newline));
            Environment variables are stored in or retrieved from the Hkey_current_user\environment entry in the Windows operating system registry.
            IDictionary Dicuser = Environment.getenvironmentvariables (Environmentvariabletarget.user); This.rtbVaribles.AppendText (String.
            Format ("{0}: {1}", "User environment variable", newline)); foreach (String str in Dicuser.keys) {string val = Dicuser[str].
                ToString (); This.rtbVaribles.AppendText (String.
            Format ("{0}: {1}{2}", str, Val, newline)); } this.rtbVaribles.AppendText (String. Format ("{0}{1}", ">>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>
            >>>>>> ", newline)); IDictionary DICProcess = Environment.getenvironmentvariables (environmentvariabletarget.process); This.rtbVaribles.AppendText (String.
            Format ("{0}: {1}", "Process environment variable", newline)); foreach (String str in Dicprocess.keys) {string val = Dicprocess[str].
                ToString (); This.rtbVaribles.AppendText (String.
            Format ("{0}: {1}{2}", str, Val, newline));
            }//Special directory string[] names = Enum.getnames (typeof (Environment.SpecialFolder));
                foreach (string name in Names) {Environment.SpecialFolder SF; if (enum.tryparse<environment.specialfolder> (name, out SF)) {String folder = En Vironment.
                    GetFolderPath (SF); This.rtbFolders.AppendText (String.
                Format ("{0}: {1}{2}", name, folder, newline));
        }//Get other hardware, software information getphicnalinfo (); private String Getosversion (Versionver) {String strclient = ""; if (ver. Major = = 5 && ver.
            Minor = = 1 {strclient = "Win XP"; else if (ver. Major = = 6 && ver.
            Minor = = 0) {strclient = "Win Vista"; else if (ver. Major = = 6 && ver.
            Minor = = 1) {strclient = "Win 7"; else if (ver. Major = = 5 && ver.
            Minor = = 0) {strclient = "Win 2000";
            else {strclient = "unknown";
        return strclient; ///<summary>///Get system memory size///</summary>///<returns> memory size (unit m) </ returns> private int getphisicalmemory () {ManagementObjectSearcher searcher = new Manageme   Ntobjectsearcher (); Used to query some management object searcher, such as system information. Query = new SELECTQUery ("Win32_physicalmemory", "", new string[] {"Capacity"});/set query Condition Managementobjectcollection Collection = Searcher.   Get (); Gets the memory capacity managementobjectcollection.managementobjectenumerator em = collection.

            GetEnumerator ();
            Long capacity = 0; while (EM. MoveNext ()) {Managementbaseobject baseobj = em.
                Current; if (baseobj.properties["Capacity"]. Value!= null) {try {capacity = long. Parse (baseobj.properties["Capacity").
                    Value.tostring ());
                    catch {return 0;
        }} return (int) (capacity/1024/1024); }///<summary>///https://msdn.microsoft.com/en-us/library/aa394084 (vs.85). aspx///</ Summary>///<returns></returns> private int Getphicnalinfo () {ManagementClass osclass = new ManagementClass ("Win32_proces Sor ");//back several can try, there will be unexpected harvest//win32_physicalmemory/win32_keyboard/win32_computersystem/win32_operatingsystem fore Ach (managementobject obj in Osclass.getinstances ()) {propertydatacollection PDC = obj.
                Properties; foreach (Propertydata PD in PDC) {This.rtbOs.AppendText (string. Format (' {0}: {1}{2} ', PD. Name, PD. 
                Value, "\ r \ n"));
        } return 0; }
    }
}
Project Download path: https://download.csdn.net/download/xiatiancc/10300432
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.