1.WMI简介
WMI是英文Windows Management Instrumentation的简写,它的功能主要是:访问本地主机的一些信息和服务,可以管理远程计算机(当然你必须要拥有足够的权限),比如:重启,关机,关闭进程,创建进程等。
2.使用时首先添加System.Management.dll,然后引用

  1. using System.Management;
  2. using System.Threading;

在EXE的应用程序中我们可以用Application.ExeName来获取应用程序自身的文件名,那么在Windows服务中怎么获取Windows服务程序的路径?

用GetModuleFileName可以获取Windows服务程序的路径。

用WMI和轻松获取SERVICE的全面信息(包括路径)  
  单获取路径语句如下:  
  select   PathName   From   Win32_Service   Where   DisplayName   =   'YourService’

  1. string[] lvData = new string[];
  2. ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service");
  3. foreach (ManagementObject mo in searcher.Get())
  4. {
  5. lvData[] = mo["Name"].ToString();
  6. lvData[] = mo["DisplayName"].ToString();
  7. lvData[] = mo["StartMode"].ToString();
  8. if (mo["Started"].Equals(true))
  9. lvData[] = "Started";
  10. else
  11. lvData[] = "Stop";
  12. lvData[] = mo["PathName"].ToString();//StartName
  13. lvData[] = mo["StartName"].ToString();//StartName
  14. TexShowing(lvData[] + " ========== " + lvData[] + " ========== " + lvData[] + " ========== " + lvData[] + " ========== " + lvData[] + " ========== " + lvData[]);
  15. }
  1. public class WMITest : System.Web.UI.Page
  2. {
  3. protected System.Web.UI.WebControls.Button Button2;
  4. protected System.Web.UI.WebControls.Button Button3;
  5. protected System.Web.UI.WebControls.Button Button4;
  6. protected System.Web.UI.WebControls.Button Button5;
  7. protected System.Web.UI.WebControls.Button Button6;
  8. protected System.Web.UI.WebControls.Button Button7;
  9. protected System.Web.UI.WebControls.Button Button8;
  10. protected System.Web.UI.WebControls.Button Button9;
  11. protected System.Web.UI.WebControls.Button Button10;
  12. protected System.Web.UI.WebControls.Button Button11;
  13. protected System.Web.UI.WebControls.Button Button12;
  14. protected System.Web.UI.WebControls.Button Button13;
  15. protected System.Web.UI.WebControls.Button Button14;
  16. protected System.Web.UI.WebControls.Button Button15;
  17. protected System.Web.UI.WebControls.Button Button1;
  18.  
  19. private void Page_Load(object sender, System.EventArgs e)
  20. {
  21. // Put user code to initialize the page here
  22. }
  23.  
  24. #region Web Form Designer generated code
  25. override protected void OnInit(EventArgs e)
  26. {
  27. //
  28. // CODEGEN: This call is required by the ASP.NET Web Form Designer.
  29. //
  30. InitializeComponent();
  31. base.OnInit(e);
  32. }
  33.  
  34. /// <summary>
  35. /// Required method for Designer support - do not modify
  36. /// the contents of this method with the code editor.
  37. /// </summary>
  38. private void InitializeComponent()
  39. {
  40. this.Button1.Click += new System.EventHandler(this.Button1_Click);
  41. this.Button2.Click += new System.EventHandler(this.Button2_Click);
  42. this.Button3.Click += new System.EventHandler(this.Button3_Click);
  43. this.Button4.Click += new System.EventHandler(this.Button4_Click);
  44. this.Button5.Click += new System.EventHandler(this.Button5_Click);
  45. this.Button6.Click += new System.EventHandler(this.Button6_Click);
  46. this.Button7.Click += new System.EventHandler(this.Button7_Click);
  47. this.Button8.Click += new System.EventHandler(this.Button8_Click);
  48. this.Button9.Click += new System.EventHandler(this.Button9_Click);
  49. this.Button10.Click += new System.EventHandler(this.Button10_Click);
  50. this.Button11.Click += new System.EventHandler(this.Button11_Click);
  51. this.Button12.Click += new System.EventHandler(this.Button12_Click);
  52. this.Button13.Click += new System.EventHandler(this.Button13_Click);
  53. this.Button14.Click += new System.EventHandler(this.Button14_Click);
  54. this.Button15.Click += new System.EventHandler(this.Button15_Click);
  55. this.Load += new System.EventHandler(this.Page_Load);
  56.  
  57. }
  58. #endregion
  59.  
  60. #region 1.如何用WMI获得指定磁盘的容量
  61. private string DriveType(string type)
  62. {
  63. string rtntype="";
  64. switch (type)
  65. {
  66. case "":
  67. rtntype="Not Type";
  68. break;
  69. case "":
  70. rtntype="Floppy disk";
  71. break;
  72. case "":
  73. rtntype="Hard disk";
  74. break;
  75. case "":
  76. rtntype="Removable drive or network drive";
  77. break;
  78. case "":
  79. rtntype="CD-ROM";
  80. break;
  81. case "":
  82. rtntype="RAM disk";
  83. break;
  84. default :
  85. break;
  86. }
  87. return rtntype;
  88. }
  89.  
  90. private void Button1_Click(object sender, System.EventArgs e)
  91. {
  92. SelectQuery query=new SelectQuery("Select * From Win32_LogicalDisk");
  93. ManagementObjectSearcher searcher=new ManagementObjectSearcher(query);
  94. foreach(ManagementBaseObject disk in searcher.Get())
  95. {
  96. Response.Write(disk["Name"] +" "+DriveType(disk["DriveType"].ToString()) + " " + disk["VolumeName"]+"<br>");
  97. }
  98. }
  99. #endregion
  100.  
  101. #region 2.如何用WMI获得指定磁盘的容量
  102. private void Button2_Click(object sender, System.EventArgs e)
  103. {
  104. ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
  105. disk.Get();
  106. Response.Write("Logical Disk Size = " + disk["Size"] + " bytes");
  107. }
  108. #endregion
  109.  
  110. #region 3.如何列出机器中所有的共享资源
  111. private void Button3_Click(object sender, System.EventArgs e)
  112. {
  113. ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_share");
  114. foreach (ManagementObject share in searcher.Get())
  115. {
  116. Response.Write(share.GetText(TextFormat.Mof));
  117. }
  118. }
  119. #endregion
  120.  
  121. #region 4.怎样写程控制让系统中的某个文件夹共享或取消共享
  122. private void Button4_Click(object sender, System.EventArgs e)
  123. {
  124. /*首先,这需要以有相应权限的用户登录系统才行

  125. object[] obj = {"C:\\Temp","我的共享",0,10,"Dot Net 实现的共享",""};
  126. 改为
  127. object[] obj = {"C:\\Temp","我的共享",0,null,"Dot Net 实现的共享",""};
  128. 就可以实现授权给最多用户了。
  129. */
  130. ManagementClass _class = new ManagementClass(new ManagementPath("Win32_Share"));
  131. object[] obj = {"C:\\Temp","我的共享",,,"Dot Net 实现的共享",""};
  132. _class.InvokeMethod("create",obj);
  133. }
  134. #endregion
  135.  
  136. #region 5.如何获得系统服务的运行状态
  137. private void Button5_Click(object sender, System.EventArgs e)
  138. {
  139. string[] lvData = new string[];
  140. ManagementObjectSearcher searcher =new ManagementObjectSearcher("SELECT * FROM Win32_Service");
  141. foreach (ManagementObject mo in searcher.Get())
  142. {
  143. lvData[] = mo["Name"].ToString();
  144. lvData[] = mo["StartMode"].ToString();
  145. if (mo["Started"].Equals(true))
  146. lvData[] = "Started";
  147. else
  148. lvData[] = "Stop";
  149. lvData[] = mo["StartName"].ToString();
  150. Response.Write(lvData[]+lvData[]+lvData[]+lvData[]);
  151. }
  152. }
  153. #endregion
  154.  
  155. #region 6.通过WMI修改IP,而实现不用重新启动
  156. private void Button6_Click(object sender, System.EventArgs e)
  157. {
  158. ReportIP();
  159. // SwitchToDHCP();
  160. SwitchToprivate();
  161. Thread.Sleep( );
  162. ReportIP();
  163. Response.Write( "end." );
  164. }
  165.  
  166. private void SwitchToDHCP()
  167. {
  168. ManagementBaseObject inPar = null;
  169. ManagementBaseObject outPar = null;
  170. ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  171. ManagementObjectCollection moc = mc.GetInstances();
  172. foreach( ManagementObject mo in moc )
  173. {
  174. if( ! (bool) mo["IPEnabled"] )
  175. continue;
  176.  
  177. inPar = mo.GetMethodParameters("EnableDHCP");
  178. outPar = mo.InvokeMethod( "EnableDHCP", inPar, null );
  179. break;
  180. }
  181. }
  182.  
  183. private void SwitchToprivate()
  184. {
  185. ManagementBaseObject inPar = null;
  186. ManagementBaseObject outPar = null;
  187. ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  188. ManagementObjectCollection moc = mc.GetInstances();
  189. foreach( ManagementObject mo in moc )
  190. {
  191. if( ! (bool) mo[ "IPEnabled" ] )
  192. continue;
  193.  
  194. inPar = mo.GetMethodParameters( "Enableprivate" );
  195. inPar["IPAddress"] = new string[] { "192.168.1.1" };
  196. inPar["SubnetMask"] = new string[] { "255.255.255.0" };
  197. outPar = mo.InvokeMethod( "Enableprivate", inPar, null );
  198. break;
  199. }
  200. }
  201.  
  202. private void ReportIP()
  203. {
  204. Response.Write( "****** Current IP addresses:" );
  205. ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  206. ManagementObjectCollection moc = mc.GetInstances();
  207. foreach( ManagementObject mo in moc )
  208. {
  209. if( ! (bool) mo[ "IPEnabled" ] )
  210. continue;
  211.  
  212. string str="{0}\n SVC: '{1}' MAC: [{2}]";
  213. str= string.Format(mo["Caption"].ToString(), mo["ServiceName"].ToString(),mo["MACAddress"].ToString());
  214.  
  215. Response.Write(str);
  216.  
  217. string[] addresses = (string[]) mo[ "IPAddress" ];
  218. string[] subnets = (string[]) mo[ "IPSubnet" ];
  219.  
  220. Response.Write( " Addresses :" );
  221. foreach(string sad in addresses)
  222. Response.Write(sad+"<br>");
  223.  
  224. Response.Write( " Subnets :" );
  225. foreach(string sub in subnets )
  226. Response.Write(sub+"<br>");
  227. }
  228. }
  229. #endregion
  230.  
  231. #region 7.如何利用WMI远程重启远程计算机
  232. private void Button7_Click(object sender, System.EventArgs e)
  233. {
  234. Response.Write("Computer details retrieved using Windows Management Instrumentation (WMI)");
  235. Response.Write("mailto:singlepine@hotmail.com");
  236. Response.Write("=========================================================================");
  237. //连接远程计算机
  238. ConnectionOptions co = new ConnectionOptions();
  239. co.Username = "john";
  240. co.Password = "john";
  241. System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\192.168.1.2\\root\\cimv2", co);
  242. //查询远程计算机
  243. System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem");
  244.  
  245. ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms,oq);
  246. ManagementObjectCollection queryCollection1 = query1.Get();
  247. foreach( ManagementObject mo in queryCollection1 )
  248. {
  249. string[] ss={""};
  250. mo.InvokeMethod("Reboot",ss);
  251. Response.Write(mo.ToString());
  252. }
  253. }
  254. #endregion
  255.  
  256. #region 8.利用WMI创建一个新的进程
  257. private void Button8_Click(object sender, System.EventArgs e)
  258. {
  259. //Get the object on which the method will be invoked
  260. ManagementClass processClass = new ManagementClass("Win32_Process");
  261.  
  262. //Get an input parameters object for this method
  263. ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
  264.  
  265. //Fill in input parameter values
  266. inParams["CommandLine"] = "calc.exe";
  267.  
  268. //Execute the method
  269. ManagementBaseObject outParams = processClass.InvokeMethod ("Create", inParams, null);
  270.  
  271. //Display results
  272. //Note: The return code of the method is provided in the "returnvalue" property of the outParams object
  273. Response.Write("Creation of calculator process returned: " + outParams["returnvalue"]);
  274. Response.Write("Process ID: " + outParams["processId"]);
  275.  
  276. }
  277. #endregion
  278.  
  279. #region 9.如何通过WMI终止一个进程
  280. private void Button9_Click(object sender, System.EventArgs e)
  281. {
  282. ManagementObject service =
  283. new ManagementObject("win32_service=\"winmgmt\"");
  284. InvokeMethodOptions options = new InvokeMethodOptions();
  285. options.Timeout = new TimeSpan(,,,);
  286.  
  287. ManagementBaseObject outParams = service.InvokeMethod("StopService", null, options);
  288.  
  289. Response.Write("Return Status = " + outParams["Returnvalue"]);
  290. }
  291. #endregion
  292.  
  293. #region 10.如何用WMI 来获取远程机器的目录以及文件
  294. private void Button10_Click(object sender, System.EventArgs e)
  295. {
  296. ManagementObject disk = new ManagementObject(
  297.  
  298. "win32_logicaldisk.deviceid=\"c:\"");
  299.  
  300. disk.Get();
  301.  
  302. Response.Write("Logical Disk Size = " + disk["Size"] + " bytes");
  303. }
  304. #endregion
  305.  
  306. #region 11.网卡的MAC地址
  307. private void Button11_Click(object sender, System.EventArgs e)
  308. {
  309. ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  310. ManagementObjectCollection moc = mc.GetInstances();
  311. foreach(ManagementObject mo in moc)
  312. {
  313. if((bool)mo["IPEnabled"] == true)
  314. Response.Write("MAC address"+mo["MacAddress"].ToString()+"<br>");
  315. mo.Dispose();
  316. }
  317. }
  318. #endregion
  319.  
  320. #region 12.CPU的系列号
  321. private void Button12_Click(object sender, System.EventArgs e)
  322. {
  323. string cpuInfo = "";//cpu序列号
  324. ManagementClass cimobject = new ManagementClass("Win32_Processor");
  325. ManagementObjectCollection moc = cimobject.GetInstances();
  326. foreach(ManagementObject mo in moc)
  327. {
  328. cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
  329. Response.Write(cpuInfo);
  330. }
  331. }
  332. #endregion
  333.  
  334. #region 13.主板的系列号
  335. private void Button13_Click(object sender, System.EventArgs e)
  336. {
  337. ManagementObjectSearcher searcher=new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
  338. foreach(ManagementObject share in searcher.Get())
  339. {
  340. Response.Write("主板制造商:" + share["Manufacturer"].ToString()) ;
  341. Response.Write("型号:" +share["Product"].ToString()) ;
  342. Response.Write("序列号:"+share["SerialNumber"].ToString()) ;
  343. }
  344. }
  345. #endregion
  346.  
  347. #region 14.获取硬盘ID
  348. private void Button14_Click(object sender, System.EventArgs e)
  349. {
  350. String HDid;
  351. ManagementClass cimobject = new ManagementClass("Win32_DiskDrive");
  352. ManagementObjectCollection moc = cimobject.GetInstances();
  353. foreach(ManagementObject mo in moc)
  354. {
  355. HDid = (string)mo.Properties["Model"].Value;
  356. Response.Write(HDid);
  357. }
  358. }
  359. #endregion
  360.  
  361. #region 15.获取本机的用户列表
  362. private void Button15_Click(object sender, System.EventArgs e)
  363. {
  364. SelectQuery query = new SelectQuery("SELECT * FROM Win32_UserAccount");
  365. ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
  366. foreach(ManagementObject os in searcher.Get())
  367. {
  368. Response.Write(os["Name"]);
  369. }
  370. }
  371. #endregion
  372. }

C# 查询Windows Service 信息 ,所在目录 启动状态的更多相关文章

  1. .Net C# Windows Service于server无法启动,错误 193:0xc1

    1.情况说明:的近期发展windows维修,当地win7系统正常.把server安装会失败. 图中的引导失败的例子.: 解决方法:执行->输入:eventvwr.msc    打开你的事件查看器 ...

  2. C#中级-Windows Service程序安装注意事项

    一.前言 这周除了改写一些识别算法外,继续我的Socket服务编写.服务器端的Socket服务是以Windows Service的形式运行的. 在我完成Windows Service编写后,启动服务时 ...

  3. Windows Service 学习系列(二):C# windows服务:安装、卸载、启动和停止Windows Service几种方式

    一.通过InstallUtil.exe安装.卸载.启动.停止Windows Service 方法一 1.以管理员身份运行cmd 2.安装windows服务 切换cd C:\Windows\Micros ...

  4. C#Windows Service服务程序的安装/卸载、启动/停止 桌面客户端管理程序设计

    C#Windows Service服务程序的安装/卸载.启动/停止 桌面客户端管理程序设计 关于Windows Service程序的安装与卸载如果每次使用命令行操作,那简直要奔溃了,太麻烦而且还容易出 ...

  5. war包部署在tomcat下,使用windows service服务方式启动tomcat服务器,在包含调用dll的模块,报dll找不到问题的解决办法

    问题描述: 开发了一个需要调用dll的java web程序,在idea开发环境下运行调试没问题,可以正常运行,在tomcat/bin下,运行批处理startup.bat,启动tomcat服务器,也可以 ...

  6. Windows批处理以服务的方式启动解决思路(ShadowsockR注册成Windows Service)

    我以ShadowsockR的server启动来解释: 由于这东西是python,如果要启动,可以写一个批处理(python.exe server.py)来启动,但是我观察发现启动的时候是附带pytho ...

  7. Windows服务器Pyton辅助运维--01.自动Copy文件(文件夹)到远程服务器所在目录

    Windows服务器Pyton辅助运维 01.自动Copy文件(文件夹)到远程服务器所在目录 开发环境: u  Web服务器: Windows Server 2008 R2 SP1 IIS 7.5 u ...

  8. windows Service启动带有管理员权限的GUI进程

    事情是这样的,公司的产品有个守护进程(windows Service)需要启动产品的主程序exe,让主程序它运行为管理员权限(因为主程序会加载一个插件,插件中有列出端口监听的功能,需要由端口查找到进程 ...

  9. 如何在HPUX的终端提示符前显示当前登录用户信息和所在目录

    修改/etc/default/profile文件,在最后加上如下内容: case $LOGNAME in     'root')     PS1="$LOGNAME@$(hostname): ...

随机推荐

  1. php 分析Session无效的原因

    Session在开发中是非常重要的一个数据存储变量了,它可以实现不同页面之间的传值了,下面我们来为各位介绍在使用Session时碰到过期无效的一些问题吧. PHP开发过程中,可能有朋友经常会遇到Ses ...

  2. docker-tomcat-nginx 反向代理和负载均衡

    1.部署tomcat镜像 下载官方的tomcat镜像. -jre7 启动docker容器,2个实例,分别映射不同的端口号, ~/work/sample-webapps/[v1.0|v2.0]/下面存放 ...

  3. 使用Donut Caching和Donut Hole Caching在ASP.NET MVC应用中缓存页面

    Donut Caching是缓存除了部分内容以外的整个页面的最好的方式,在它出现之前,我们使用"输出缓存"来缓存整个页面. 何时使用Donut Caching 假设你有一个应用程序 ...

  4. nginx+lua+redis初体验

    1.下载nginx.lua.redis nginx下载地址 wget  http://nginx.org/download/nginx-1.8.0.tar.gz lua下载地址 wget http:/ ...

  5. MySQL(二)

    一.外键 外键是设置当前表中的某一列与别一数据表中的主键列关联.主要目的是控制与外键表中的数据,保持数据一致性,完整性,也就是说:当前表中这一列的数据必须是关联外键列中的某一数据,而且相关联的两个数据 ...

  6. SQL基本语句(2)

    使用Insert语句插入新数据 语法:INSERT [INTO] tbl_name [(col_name,...)] VALUES (pression,...),… INSERT [INTO] tbl ...

  7. 自定义PageControl样式

    #define iOS7 ([[UIDevice currentDevice].systemVersion doubleValue] >= 7.0) //调用方法 改变PageControl样式 ...

  8. 虚拟内存和swap分区的关系

    首先,这两个概念分别对应windows和linux,即:windows:虚拟内存linux:swap分区 windows即使物理内存没有用完也会去用到虚拟内存,而Linux不一样 Linux只有当物理 ...

  9. JS 点击按钮后弹出遮罩层,有关闭按钮

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <t ...

  10. asp.net(c#)修改时的赋值操作

    赋值操作方法(将信息显示至文本框中): public void Show_Infobase(int _peoid) { DataSet ds = new DataSet(); ds = platbll ...