C# 查询Windows Service 信息 ,所在目录 启动状态

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

using System.Management;

using System.Threading; 

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

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

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

                string[] lvData = new string[6];

                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service");

                foreach (ManagementObject mo in searcher.Get())

                {

                    lvData[0] = mo["Name"].ToString();

                    lvData[1] = mo["DisplayName"].ToString();

                    lvData[2] = mo["StartMode"].ToString();

                    if (mo["Started"].Equals(true))

                        lvData[3] = "Started";

                    else

                        lvData[3] = "Stop";

                    lvData[4] = mo["PathName"].ToString();//StartName

                    lvData[5] = mo["StartName"].ToString();//StartName

                    TexShowing(lvData[0] + " ========== " + lvData[1] + " ========== " + lvData[2] + " ========== " + lvData[3] + " ========== " + lvData[4] + " ========== " + lvData[5]);

                }
  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 "1":

 67                     rtntype="Not Type";

 68                     break;

 69                 case "2":

 70                     rtntype="Floppy disk";

 71                     break;

 72                 case "3":

 73                     rtntype="Hard disk";

 74                     break;

 75                 case "4":

 76                     rtntype="Removable drive or network drive";

 77                     break;

 78                 case "5":

 79                     rtntype="CD-ROM";

 80                     break;

 81                 case "6":

 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 126             object[] obj = {"C:\\Temp","我的共享",0,10,"Dot Net 实现的共享",""}; 

127             改为 

128             object[] obj = {"C:\\Temp","我的共享",0,null,"Dot Net 实现的共享",""}; 

129             就可以实现授权给最多用户了。

130             */

131             ManagementClass _class = new ManagementClass(new ManagementPath("Win32_Share"));

132             object[] obj = {"C:\\Temp","我的共享",0,10,"Dot Net 实现的共享",""};

133             _class.InvokeMethod("create",obj); 

134         }

135         #endregion

136 

137         #region 5.如何获得系统服务的运行状态

138         private void Button5_Click(object sender, System.EventArgs e)

139         {

140             string[] lvData =  new string[4];            

141             ManagementObjectSearcher searcher =new ManagementObjectSearcher("SELECT * FROM Win32_Service"); 

142             foreach (ManagementObject mo in searcher.Get()) 

143             { 

144                 lvData[0] = mo["Name"].ToString(); 

145                 lvData[1] = mo["StartMode"].ToString(); 

146                 if (mo["Started"].Equals(true)) 

147                     lvData[2] = "Started"; 

148                 else 

149                     lvData[2] = "Stop"; 

150                 lvData[3] = mo["StartName"].ToString(); 

151                 Response.Write(lvData[0]+lvData[1]+lvData[2]+lvData[3]);                    

152             }             

153         }

154         #endregion

155 

156         #region 6.通过WMI修改IP,而实现不用重新启动

157         private void Button6_Click(object sender, System.EventArgs e)

158         {

159             ReportIP(); 

160             // SwitchToDHCP(); 

161             SwitchToprivate(); 

162             Thread.Sleep( 5000 ); 

163             ReportIP(); 

164             Response.Write( "end." );

165         }        

166         

167         private void SwitchToDHCP() 

168         { 

169             ManagementBaseObject inPar = null; 

170             ManagementBaseObject outPar = null; 

171             ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); 

172             ManagementObjectCollection moc = mc.GetInstances(); 

173             foreach( ManagementObject mo in moc ) 

174             { 

175                 if( ! (bool) mo["IPEnabled"] ) 

176                     continue; 

177 

178                 inPar = mo.GetMethodParameters("EnableDHCP"); 

179                 outPar = mo.InvokeMethod( "EnableDHCP", inPar, null ); 

180                 break; 

181             } 

182         } 

183 

184         private void SwitchToprivate() 

185         { 

186             ManagementBaseObject inPar = null; 

187             ManagementBaseObject outPar = null; 

188             ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); 

189             ManagementObjectCollection moc = mc.GetInstances(); 

190             foreach( ManagementObject mo in moc ) 

191             { 

192                 if( ! (bool) mo[ "IPEnabled" ] ) 

193                     continue; 

194 

195                 inPar = mo.GetMethodParameters( "Enableprivate" ); 

196                 inPar["IPAddress"] = new string[] { "192.168.1.1" }; 

197                 inPar["SubnetMask"] = new string[] { "255.255.255.0" }; 

198                 outPar = mo.InvokeMethod( "Enableprivate", inPar, null ); 

199                 break; 

200             } 

201         } 

202 

203         private void ReportIP() 

204         { 

205             Response.Write( "****** Current IP addresses:" ); 

206             ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); 

207             ManagementObjectCollection moc = mc.GetInstances(); 

208             foreach( ManagementObject mo in moc ) 

209             { 

210                 if( ! (bool) mo[ "IPEnabled" ] ) 

211                     continue; 

212 

213                 string str="{0}\n SVC: '{1}' MAC: [{2}]";

214                 str= string.Format(mo["Caption"].ToString(), mo["ServiceName"].ToString(),mo["MACAddress"].ToString());

215 

216                 Response.Write(str); 

217 

218                 string[] addresses = (string[]) mo[ "IPAddress" ]; 

219                 string[] subnets = (string[]) mo[ "IPSubnet" ]; 

220 

221                 Response.Write( " Addresses :" ); 

222                 foreach(string sad in addresses) 

223                     Response.Write(sad+"<br>"); 

224 

225                 Response.Write( " Subnets :" ); 

226                 foreach(string sub in subnets ) 

227                     Response.Write(sub+"<br>"); 

228             } 

229         }

230         #endregion

231 

232         #region 7.如何利用WMI远程重启远程计算机

233         private void Button7_Click(object sender, System.EventArgs e)

234         {

235             Response.Write("Computer details retrieved using Windows Management Instrumentation (WMI)"); 

236             Response.Write("mailto:[email protected]"); 

237             Response.Write("=========================================================================");  

238             //连接远程计算机 

239             ConnectionOptions co = new ConnectionOptions(); 

240             co.Username = "john"; 

241             co.Password = "john"; 

242             System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\192.168.1.2\\root\\cimv2", co);       

243             //查询远程计算机 

244             System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem"); 

245                    

246             ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms,oq); 

247             ManagementObjectCollection queryCollection1 = query1.Get();             

248             foreach( ManagementObject mo in queryCollection1 )  

249             { 

250                 string[] ss={""}; 

251                 mo.InvokeMethod("Reboot",ss); 

252                 Response.Write(mo.ToString()); 

253             } 

254         }

255         #endregion

256 

257         #region 8.利用WMI创建一个新的进程

258         private void Button8_Click(object sender, System.EventArgs e)

259         {

260             //Get the object on which the method will be invoked 

261             ManagementClass processClass = new ManagementClass("Win32_Process"); 

262 

263             //Get an input parameters object for this method 

264             ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); 

265 

266             //Fill in input parameter values 

267             inParams["CommandLine"] = "calc.exe"; 

268 

269             //Execute the method 

270             ManagementBaseObject outParams = processClass.InvokeMethod ("Create", inParams, null); 

271 

272             //Display results 

273             //Note: The return code of the method is provided in the "returnvalue" property of the outParams object 

274             Response.Write("Creation of calculator process returned: " + outParams["returnvalue"]); 

275             Response.Write("Process ID: " + outParams["processId"]); 

276 

277         }

278         #endregion

279 

280         #region 9.如何通过WMI终止一个进程

281         private void Button9_Click(object sender, System.EventArgs e)

282         {

283             ManagementObject service =  

284                 new ManagementObject("win32_service=\"winmgmt\""); 

285             InvokeMethodOptions options = new InvokeMethodOptions(); 

286             options.Timeout = new TimeSpan(0,0,0,5);  

287 

288             ManagementBaseObject outParams = service.InvokeMethod("StopService", null, options);

289 

290             Response.Write("Return Status = " + outParams["Returnvalue"]);

291         }

292         #endregion

293 

294         #region 10.如何用WMI 来获取远程机器的目录以及文件

295         private void Button10_Click(object sender, System.EventArgs e)

296         {

297             ManagementObject disk = new ManagementObject(

298 

299                 "win32_logicaldisk.deviceid=\"c:\"");

300 

301             disk.Get();

302 

303             Response.Write("Logical Disk Size = " + disk["Size"] + " bytes");

304         }

305         #endregion

306 

307         #region 11.网卡的MAC地址

308         private void Button11_Click(object sender, System.EventArgs e)

309         {

310             ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); 

311             ManagementObjectCollection moc = mc.GetInstances(); 

312             foreach(ManagementObject mo in moc) 

313             { 

314                 if((bool)mo["IPEnabled"] == true) 

315                     Response.Write("MAC address"+mo["MacAddress"].ToString()+"<br>"); 

316                 mo.Dispose(); 

317             } 

318         }

319         #endregion

320 

321         #region 12.CPU的系列号 

322         private void Button12_Click(object sender, System.EventArgs e)

323         {

324             string cpuInfo = "";//cpu序列号 

325             ManagementClass cimobject = new ManagementClass("Win32_Processor"); 

326             ManagementObjectCollection moc = cimobject.GetInstances(); 

327             foreach(ManagementObject mo in moc) 

328             { 

329                 cpuInfo = mo.Properties["ProcessorId"].Value.ToString(); 

330                 Response.Write(cpuInfo);

331             } 

332         }

333         #endregion

334 

335         #region 13.主板的系列号

336         private void Button13_Click(object sender, System.EventArgs e)

337         {

338             ManagementObjectSearcher searcher=new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");

339             foreach(ManagementObject share in searcher.Get())

340             {

341                 Response.Write("主板制造商:" + share["Manufacturer"].ToString()) ;

342                 Response.Write("型号:" +share["Product"].ToString()) ;

343                 Response.Write("序列号:"+share["SerialNumber"].ToString()) ;

344             }

345         }

346         #endregion

347 

348         #region 14.获取硬盘ID

349         private void Button14_Click(object sender, System.EventArgs e)

350         {

351             String HDid; 

352             ManagementClass cimobject = new ManagementClass("Win32_DiskDrive"); 

353             ManagementObjectCollection moc = cimobject.GetInstances(); 

354             foreach(ManagementObject mo in moc) 

355             { 

356                 HDid = (string)mo.Properties["Model"].Value; 

357                 Response.Write(HDid);  

358             } 

359         }

360         #endregion

361 

362         #region 15.获取本机的用户列表

363         private void Button15_Click(object sender, System.EventArgs e)

364         {

365             SelectQuery query = new SelectQuery("SELECT * FROM Win32_UserAccount");

366             ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

367             foreach(ManagementObject os in searcher.Get())

368             {

369                 Response.Write(os["Name"]);

370             }

371         }

372         #endregion

373     }
View Code

 

你可能感兴趣的:(windows)