




已阅读5页,还剩15页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
用C#获取各类系统环境信息的方法研究By xfStudio2016年3月5日星期六最近对“如何利用C#获取系统有关环境和属性这个问题”进行研究。这个也是在网上问得比较多的问题,通过查阅各类资料,进行了初步研究,整理了一篇小文章。目录1获取CPU编号、硬盘编号等系统有关环境、属性12 C#获取当前应用程序所在路径及环境变量112.1 获取当前文件的路径112.2 操作环境变量123 获取本机电脑名称和IP地址124 获取系统所有服务信息155 获取系统进程信息171获取CPU编号、硬盘编号等系统有关环境、属性首先需要定义几个结构(struct),便于DllImport作为返回参数调用。以下是代码:CpuInfo.csusingSystem;usingSystem.Configuration;usingSystem.Runtime.InteropServices;/*/* LayoutKind.Automatic:为了提高效率允许运行态对类型成员重新排序* 注意:永远不要使用这个选项来调用不受管辖的动态链接库函数。* LayoutKind.Explicit:对每个域按照FieldOffset属性对类型成员排序* LayoutKind.Sequential:对出现在受管辖类型定义地方的不受管辖内存中的类型成员进行排序。*/*/ /定义CPU的信息结构/ StructLayout(LayoutKind.Sequential)publicstructCpuInfo./*/ /OEM ID/ publicuintdwOemId;/*/ /页面大小/ publicuintdwPageSize;publicuintlpMinimumApplicationAddress;publicuintlpMaximumApplicationAddress;publicuintdwActiveProcessorMask;/*/ /CPU个数/ publicuintdwNumberOfProcessors;/*/ /CPU类型/ publicuintdwProcessorType;publicuintdwAllocationGranularity;/*/ /CPU等级/ publicuintdwProcessorLevel;publicuintdwProcessorRevision;MemoryInfo.csusingSystem;usingSystem.Configuration;usingSystem.Runtime.InteropServices;/*/* LayoutKind.Automatic:为了提高效率允许运行态对类型成员重新排序* 注意:永远不要使用这个选项来调用不受管辖的动态链接库函数。* LayoutKind.Explicit:对每个域按照FieldOffset属性对类型成员排序* LayoutKind.Sequential:对出现在受管辖类型定义地方的不受管辖内存中的类型成员进行排序。*/*/ /定义内存的信息结构/ StructLayout(LayoutKind.Sequential)publicstructMemoryInfo./*/ / publicuintdwLength;/*/ /已经使用的内存/ publicuintdwMemoryLoad;/*/ /总物理内存大小/ publicuintdwTotalPhys;/*/ /可用物理内存大小/ publicuintdwAvailPhys;/*/ /交换文件总大小/ publicuintdwTotalPageFile;/*/ /可用交换文件大小/ publicuintdwAvailPageFile;/*/ /总虚拟内存大小/ publicuintdwTotalVirtual;/*/ /可用虚拟内存大小/ publicuintdwAvailVirtual;SystemTimeInfo.csusingSystem;usingSystem.Configuration;usingSystem.Runtime.InteropServices;/*/* LayoutKind.Automatic:为了提高效率允许运行态对类型成员重新排序* 注意:永远不要使用这个选项来调用不受管辖的动态链接库函数。* LayoutKind.Explicit:对每个域按照FieldOffset属性对类型成员排序* LayoutKind.Sequential:对出现在受管辖类型定义地方的不受管辖内存中的类型成员进行排序。*/*/ /定义系统时间的信息结构/ StructLayout(LayoutKind.Sequential)publicstructSystemTimeInfo./*/ /年/ publicushortwYear;/*/ /月/ publicushortwMonth;/*/ /星期/ publicushortwDayOfWeek;/*/ /天/ publicushortwDay;/*/ /小时/ publicushortwHour;/*/ /分钟/ publicushortwMinute;/*/ /秒/ publicushortwSecond;/*/ /毫秒/ publicushortwMilliseconds;另外还定义了一个调用类SystemInfo.cs,代码如下:usingSystem;usingSystem.Configuration;usingSystem.Runtime.InteropServices;usingSystem.Management;usingSystem.Text;/*/ /SystemInfo 的摘要说明/ publicclassSystemInfo.privateconstintCHAR_COUNT = 128;publicSystemInfo().DllImport(kernel32)privatestaticexternvoidGetWindowsDirectory(StringBuilder WinDir,intcount);DllImport(kernel32)privatestaticexternvoidGetSystemDirectory(StringBuilder SysDir,intcount);DllImport(kernel32)privatestaticexternvoidGetSystemInfo(refCpuInfo cpuInfo);DllImport(kernel32)privatestaticexternvoidGlobalMemoryStatus(refMemoryInfo memInfo);DllImport(kernel32)privatestaticexternvoidGetSystemTime(refSystemTimeInfo sysInfo);/*/ /查询CPU编号/ / publicstringGetCpuId().ManagementClass mClass =newManagementClass(Win32_Processor);ManagementObjectCollection moc = mClass.GetInstances();stringcpuId=null;foreach(ManagementObject moinmoc).cpuId = mo.PropertiesProcessorId.Value.ToString();break;returncpuId;/*/ /查询硬盘编号/ / publicstringGetMainHardDiskId().ManagementObjectSearcher searcher =newManagementObjectSearcher(SELECT * FROM Win32_PhysicalMedia);String hardDiskID=null;foreach(ManagementObject moinsearcher.Get().hardDiskID = moSerialNumber.ToString().Trim();break;returnhardDiskID;/*/ /获取Windows目录/ / publicstringGetWinDirectory().StringBuilder sBuilder =newStringBuilder(CHAR_COUNT);GetWindowsDirectory(sBuilder, CHAR_COUNT);returnsBuilder.ToString();/*/ /获取系统目录/ / publicstringGetSysDirectory().StringBuilder sBuilder =newStringBuilder(CHAR_COUNT);GetSystemDirectory(sBuilder, CHAR_COUNT);returnsBuilder.ToString(); /*/ /获取CPU信息/ / publicCpuInfo GetCpuInfo().CpuInfo cpuInfo =newCpuInfo();GetSystemInfo(refcpuInfo);returncpuInfo;/*/ /获取系统内存信息/ / publicMemoryInfo GetMemoryInfo().MemoryInfo memoryInfo =newMemoryInfo();GlobalMemoryStatus(refmemoryInfo);returnmemoryInfo;/*/ /获取系统时间信息/ / publicSystemTimeInfo GetSystemTimeInfo().SystemTimeInfo systemTimeInfo =newSystemTimeInfo();GetSystemTime(refsystemTimeInfo);returnsystemTimeInfo;/*/ /获取系统名称/ / publicstringGetOperationSystemInName().OperatingSystem os = System.Environment.OSVersion;stringosName =UNKNOWN;switch(os.Platform).casePlatformID.Win32Windows:switch(os.Version.Minor).case0: osName =Windows 95;break;case10: osName =Windows 98;break;case90: osName =Windows ME;break;break;casePlatformID.Win32NT:switch(os.Version.Major).case3: osName =Windws NT 3.51;break;case4: osName =Windows NT 4;break;case5:if(os.Version.Minor = 0).osName =Windows 2000;elseif(os.Version.Minor = 1).osName =Windows XP;elseif(os.Version.Minor = 2).osName =Windows Server 2003;break;case6: osName =Longhorn;break;break;returnString.Format(0,1, osName, os.Version.ToString();以下是调用实例,为了简单,我在一个aspx页面中输出,不过这个程序可以在WinForm中调用:usingSystem;usingSystem.Data;usingSystem.Configuration;usingSystem.Collections;usingSystem.Collections.Specialized;usingSystem.Web;usingSystem.Web.Security;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Web.UI.WebControls.WebParts;usingSystem.Web.UI.HtmlControls;usingSystem.Runtime.InteropServices;publicpartialclassIndex : System.Web.UI.PtectedvoidPage_Load(objectsender, EventArgs e).if(!Page.IsPostBack).SystemInfo systemInfo =newSystemInfo(); Response.Write(操作系统:+ systemInfo.GetOperationSystemInName() +);Response.Write(CPU编号:+systemInfo.GetCpuId() +);Response.Write(硬盘编号:+systemInfo.GetMainHardDiskId() +);Response.Write(Windows目录所在位置:+ systemInfo.GetSysDirectory() +);Response.Write(系统目录所在位置:+ systemInfo.GetWinDirectory() +);MemoryInfo memoryInfo = systemInfo.GetMemoryInfo();CpuInfo cpuInfo = systemInfo.GetCpuInfo();Response.Write(dwActiveProcessorMask+ cpuInfo.dwActiveProcessorMask +);Response.Write(dwAllocationGranularity+ cpuInfo.dwAllocationGranularity +);Response.Write(CPU个数:+ cpuInfo.dwNumberOfProcessors +);Response.Write(OEM ID:+ cpuInfo.dwOemId +);Response.Write(页面大小+ cpuInfo.dwPageSize +);Response.Write(CPU等级+ cpuInfo.dwProcessorLevel +);Response.Write(dwProcessorRevision+ cpuInfo.dwProcessorRevision +);Response.Write(CPU类型+ cpuInfo.dwProcessorType +);Response.Write(lpMaximumApplicationAddress+ cpuInfo.lpMaximumApplicationAddress +);Response.Write(lpMinimumApplicationAddress+ cpuInfo.lpMinimumApplicationAddress +);Response.Write(CPU类型:+ cpuInfo.dwProcessorType +);Response.Write(可用交换文件大小:+ memoryInfo.dwAvailPageFile +);Response.Write(可用物理内存大小:+ memoryInfo.dwAvailPhys +);Response.Write(可用虚拟内存大小+ memoryInfo.dwAvailVirtual +);Response.Write(操作系统位数:+ memoryInfo.dwLength +);Response.Write(已经使用内存大小:+ memoryInfo.dwMemoryLoad +);Response.Write(交换文件总大小:+ memoryInfo.dwTotalPageFile +);Response.Write(总物理内存大小:+ memoryInfo.dwTotalPhys +);Response.Write(总虚拟内存大小:+ memoryInfo.dwTotalVirtual +);2 C#获取当前应用程序所在路径及环境变量2.1 获取当前文件的路径string str1=Process.GetCurrentProcess().MainModule.FileName;/可获得当前执行的exe的文件名。string str2=Environment.CurrentDirectory;/获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。(备注:按照定义,如果该进程在本地或网络驱动器的根目录中启动,则此属性的值为驱动器名称后跟一个尾部反斜杠(如“C:”)。如果该进程在子目录中启动,则此属性的值为不带尾部反斜杠的驱动器和子目录路径如“C:mySubDirectory”)。string str3=Directory.GetCurrentDirectory();/获取应用程序的当前工作目录。string str4=AppDomain.CurrentDomain.BaseDirectory;/获取基目录,它由程序集冲突解决程序用来探测程序集。string str5=Application.StartupPath;/获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。string str6=Application.ExecutablePath;/获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。string str7=AppDomain.CurrentDomain.SetupInformation.ApplicationBase;/获取或设置包含该应用程序的目录的名称。1. System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName 获取模块的完整路径。2. System.Environment.CurrentDirectory 获取和设置当前目录(该进程从中启动的目录)的完全限定目录。3. System.IO.Directory.GetCurrentDirectory() 获取应用程序的当前工作目录。这个不一定是程序从中启动的目录啊,有可能程序放在C:www里,这个函数有可能返回C:Documents and SettingsZYB,或者C:Program FilesAdobe,有时不一定返回什么东东,这是任何应用程序最后一次操作过的目录,比如你用Word打开了E:docmy.doc这个文件,此时执行这个方法就返回了E:doc了。4. System.AppDomain.CurrentDomain.BaseDirectory 获取程序的基目录。5. System.Windows.Forms.Application.StartupPath 获取启动了应用程序的可执行文件的路径。效果和2、5一样。只是5返回的字符串后面多了一个而已。6. System.Windows.Forms.Application.ExecutablePath 获取启动了应用程序的可执行文件的路径及文件名,效果和1一样。7. System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase 获取和设置包括该应用程序的目录的名称。2.2 操作环境变量利用System.Environment.GetEnvironmentVariable()方法可以很方便地取得系统环境变量,如:System.Environment.GetEnvironmentVariable(windir)就可以取得windows系统目录的路径。以下是一些常用的环境变量取值:System.Environment.GetEnvironmentVariable(windir);System.Environment.GetEnvironmentVariable(INCLUDE);System.Environment.GetEnvironmentVariable(TMP);System.Environment.GetEnvironmentVariable(TEMP);System.Environment.GetEnvironmentVariable(Path);3 获取本机电脑名称和IP地址using System;using System.Collections.Generic;using System.Text;using System.Net; /需要引用.Net命名空间 namespace ConsoleApplication1 class Program static void Main(string args) /获得主机名 string HostName = Dns.GetHostName(); Console.WriteLine(主机名是:+HostName); /遍历地址列表,如果电脑有多网卡只能这样遍历显示 IPAddress iplist=Dns.GetHostAddresses(HostName); for (int i = 0; i iplist.Length; i+) Console.WriteLine(IP地址:+iplisti); Console.ReadLine(); 1. 在ASP.NET中专用属性: 获取服务器电脑名:Page.Server.ManchineName 获取用户信息:Page.User 获取客户端电脑名:Page.Request.UserHostName 获取客户端电脑IP:Page.Request.UserHostAddress 2. 在网络编程中的通用方法: 获取当前电脑名:static System.Net.Dns.GetHostName() 根据电脑名取出全部IP地址:static System.Net.Dns.Resolve(电脑名 ).AddressList 也可根据IP地址取出电脑名:static System.Net.Dns.Resolve(IP地址 ).HostName 3. 系统环境类的通用属性: 当前电脑名:static System.Environment.MachineName 当前电脑所属网域:static System.Environment.UserDomainName 当前电脑用户:static System.Environment.UserName 4 利用System.Security.Princip al; if(User.Identity.IsAuthenticated) WindowsIdentity CurrentIdentity = WindowsIdentity.GetCurrent(); message.Text=用户的windows登陆名称:+CurrentIdentity.Name+; Response.Write(str.Substring(0,4); 4 获取系统所有服务信息核心代码:usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.ServiceProcess;namespaceStu
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 彭阳消防考试题库及答案
- 2025年贵州公务员考试行测真题及答案
- 2025年广西壮族自治区中央遴选真题及参考答案(b类)
- 淮安清中开学考试卷及答案
- 母婴护理师考试试卷题库及答案
- 信息技术考试真题分类及答案
- 医学生化考试试题及答案
- 广东春季高考考试卷子及答案
- 九江编制考试题库及答案
- 2025年医疗器械法规与管理考试试题及答案
- 《矿山安全落后工艺及设备淘汰目录(2024年)》
- 化工和危险化学品企业重大事故隐患重点排查事项清单(参考模板)
- 《公共机构建筑机电系统调适技术导则》
- 智慧农业的农田水利与水资源管理技术
- 测控技术与仪器技术面试
- 三年级数学简便计算300题及答案
- 生涯发展报告
- 企业活跃度分析报告
- 《词根词缀》课件
- 检验科标本运送培训课件
- 体育专业生涯人物访谈
评论
0/150
提交评论