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[];
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service");
foreach (ManagementObject mo in searcher.Get())
{
lvData[] = mo["Name"].ToString();
lvData[] = mo["DisplayName"].ToString();
lvData[] = mo["StartMode"].ToString();
if (mo["Started"].Equals(true))
lvData[] = "Started";
else
lvData[] = "Stop";
lvData[] = mo["PathName"].ToString();//StartName
lvData[] = mo["StartName"].ToString();//StartName
TexShowing(lvData[] + " ========== " + lvData[] + " ========== " + lvData[] + " ========== " + lvData[] + " ========== " + lvData[] + " ========== " + lvData[]);
}
public class WMITest : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button2;
protected System.Web.UI.WebControls.Button Button3;
protected System.Web.UI.WebControls.Button Button4;
protected System.Web.UI.WebControls.Button Button5;
protected System.Web.UI.WebControls.Button Button6;
protected System.Web.UI.WebControls.Button Button7;
protected System.Web.UI.WebControls.Button Button8;
protected System.Web.UI.WebControls.Button Button9;
protected System.Web.UI.WebControls.Button Button10;
protected System.Web.UI.WebControls.Button Button11;
protected System.Web.UI.WebControls.Button Button12;
protected System.Web.UI.WebControls.Button Button13;
protected System.Web.UI.WebControls.Button Button14;
protected System.Web.UI.WebControls.Button Button15;
protected System.Web.UI.WebControls.Button Button1; private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
} #region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
} /// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Button2.Click += new System.EventHandler(this.Button2_Click);
this.Button3.Click += new System.EventHandler(this.Button3_Click);
this.Button4.Click += new System.EventHandler(this.Button4_Click);
this.Button5.Click += new System.EventHandler(this.Button5_Click);
this.Button6.Click += new System.EventHandler(this.Button6_Click);
this.Button7.Click += new System.EventHandler(this.Button7_Click);
this.Button8.Click += new System.EventHandler(this.Button8_Click);
this.Button9.Click += new System.EventHandler(this.Button9_Click);
this.Button10.Click += new System.EventHandler(this.Button10_Click);
this.Button11.Click += new System.EventHandler(this.Button11_Click);
this.Button12.Click += new System.EventHandler(this.Button12_Click);
this.Button13.Click += new System.EventHandler(this.Button13_Click);
this.Button14.Click += new System.EventHandler(this.Button14_Click);
this.Button15.Click += new System.EventHandler(this.Button15_Click);
this.Load += new System.EventHandler(this.Page_Load); }
#endregion #region 1.如何用WMI获得指定磁盘的容量
private string DriveType(string type)
{
string rtntype="";
switch (type)
{
case "":
rtntype="Not Type";
break;
case "":
rtntype="Floppy disk";
break;
case "":
rtntype="Hard disk";
break;
case "":
rtntype="Removable drive or network drive";
break;
case "":
rtntype="CD-ROM";
break;
case "":
rtntype="RAM disk";
break;
default :
break;
}
return rtntype;
} private void Button1_Click(object sender, System.EventArgs e)
{
SelectQuery query=new SelectQuery("Select * From Win32_LogicalDisk");
ManagementObjectSearcher searcher=new ManagementObjectSearcher(query);
foreach(ManagementBaseObject disk in searcher.Get())
{
Response.Write(disk["Name"] +" "+DriveType(disk["DriveType"].ToString()) + " " + disk["VolumeName"]+"<br>");
}
}
#endregion #region 2.如何用WMI获得指定磁盘的容量
private void Button2_Click(object sender, System.EventArgs e)
{
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
disk.Get();
Response.Write("Logical Disk Size = " + disk["Size"] + " bytes");
}
#endregion #region 3.如何列出机器中所有的共享资源
private void Button3_Click(object sender, System.EventArgs e)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_share");
foreach (ManagementObject share in searcher.Get())
{
Response.Write(share.GetText(TextFormat.Mof));
}
}
#endregion #region 4.怎样写程控制让系统中的某个文件夹共享或取消共享
private void Button4_Click(object sender, System.EventArgs e)
{
/*首先,这需要以有相应权限的用户登录系统才行
将
object[] obj = {"C:\\Temp","我的共享",0,10,"Dot Net 实现的共享",""};
改为
object[] obj = {"C:\\Temp","我的共享",0,null,"Dot Net 实现的共享",""};
就可以实现授权给最多用户了。
*/
ManagementClass _class = new ManagementClass(new ManagementPath("Win32_Share"));
object[] obj = {"C:\\Temp","我的共享",,,"Dot Net 实现的共享",""};
_class.InvokeMethod("create",obj);
}
#endregion #region 5.如何获得系统服务的运行状态
private void Button5_Click(object sender, System.EventArgs e)
{
string[] lvData = new string[];
ManagementObjectSearcher searcher =new ManagementObjectSearcher("SELECT * FROM Win32_Service");
foreach (ManagementObject mo in searcher.Get())
{
lvData[] = mo["Name"].ToString();
lvData[] = mo["StartMode"].ToString();
if (mo["Started"].Equals(true))
lvData[] = "Started";
else
lvData[] = "Stop";
lvData[] = mo["StartName"].ToString();
Response.Write(lvData[]+lvData[]+lvData[]+lvData[]);
}
}
#endregion #region 6.通过WMI修改IP,而实现不用重新启动
private void Button6_Click(object sender, System.EventArgs e)
{
ReportIP();
// SwitchToDHCP();
SwitchToprivate();
Thread.Sleep( );
ReportIP();
Response.Write( "end." );
} private void SwitchToDHCP()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo["IPEnabled"] )
continue; inPar = mo.GetMethodParameters("EnableDHCP");
outPar = mo.InvokeMethod( "EnableDHCP", inPar, null );
break;
}
} private void SwitchToprivate()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue; inPar = mo.GetMethodParameters( "Enableprivate" );
inPar["IPAddress"] = new string[] { "192.168.1.1" };
inPar["SubnetMask"] = new string[] { "255.255.255.0" };
outPar = mo.InvokeMethod( "Enableprivate", inPar, null );
break;
}
} private void ReportIP()
{
Response.Write( "****** Current IP addresses:" );
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue; string str="{0}\n SVC: '{1}' MAC: [{2}]";
str= string.Format(mo["Caption"].ToString(), mo["ServiceName"].ToString(),mo["MACAddress"].ToString()); Response.Write(str); string[] addresses = (string[]) mo[ "IPAddress" ];
string[] subnets = (string[]) mo[ "IPSubnet" ]; Response.Write( " Addresses :" );
foreach(string sad in addresses)
Response.Write(sad+"<br>"); Response.Write( " Subnets :" );
foreach(string sub in subnets )
Response.Write(sub+"<br>");
}
}
#endregion #region 7.如何利用WMI远程重启远程计算机
private void Button7_Click(object sender, System.EventArgs e)
{
Response.Write("Computer details retrieved using Windows Management Instrumentation (WMI)");
Response.Write("mailto:singlepine@hotmail.com");
Response.Write("=========================================================================");
//连接远程计算机
ConnectionOptions co = new ConnectionOptions();
co.Username = "john";
co.Password = "john";
System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\192.168.1.2\\root\\cimv2", co);
//查询远程计算机
System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection1 = query1.Get();
foreach( ManagementObject mo in queryCollection1 )
{
string[] ss={""};
mo.InvokeMethod("Reboot",ss);
Response.Write(mo.ToString());
}
}
#endregion #region 8.利用WMI创建一个新的进程
private void Button8_Click(object sender, System.EventArgs e)
{
//Get the object on which the method will be invoked
ManagementClass processClass = new ManagementClass("Win32_Process"); //Get an input parameters object for this method
ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); //Fill in input parameter values
inParams["CommandLine"] = "calc.exe"; //Execute the method
ManagementBaseObject outParams = processClass.InvokeMethod ("Create", inParams, null); //Display results
//Note: The return code of the method is provided in the "returnvalue" property of the outParams object
Response.Write("Creation of calculator process returned: " + outParams["returnvalue"]);
Response.Write("Process ID: " + outParams["processId"]); }
#endregion #region 9.如何通过WMI终止一个进程
private void Button9_Click(object sender, System.EventArgs e)
{
ManagementObject service =
new ManagementObject("win32_service=\"winmgmt\"");
InvokeMethodOptions options = new InvokeMethodOptions();
options.Timeout = new TimeSpan(,,,); ManagementBaseObject outParams = service.InvokeMethod("StopService", null, options); Response.Write("Return Status = " + outParams["Returnvalue"]);
}
#endregion #region 10.如何用WMI 来获取远程机器的目录以及文件
private void Button10_Click(object sender, System.EventArgs e)
{
ManagementObject disk = new ManagementObject( "win32_logicaldisk.deviceid=\"c:\""); disk.Get(); Response.Write("Logical Disk Size = " + disk["Size"] + " bytes");
}
#endregion #region 11.网卡的MAC地址
private void Button11_Click(object sender, System.EventArgs e)
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach(ManagementObject mo in moc)
{
if((bool)mo["IPEnabled"] == true)
Response.Write("MAC address"+mo["MacAddress"].ToString()+"<br>");
mo.Dispose();
}
}
#endregion #region 12.CPU的系列号
private void Button12_Click(object sender, System.EventArgs e)
{
string cpuInfo = "";//cpu序列号
ManagementClass cimobject = new ManagementClass("Win32_Processor");
ManagementObjectCollection moc = cimobject.GetInstances();
foreach(ManagementObject mo in moc)
{
cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
Response.Write(cpuInfo);
}
}
#endregion #region 13.主板的系列号
private void Button13_Click(object sender, System.EventArgs e)
{
ManagementObjectSearcher searcher=new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
foreach(ManagementObject share in searcher.Get())
{
Response.Write("主板制造商:" + share["Manufacturer"].ToString()) ;
Response.Write("型号:" +share["Product"].ToString()) ;
Response.Write("序列号:"+share["SerialNumber"].ToString()) ;
}
}
#endregion #region 14.获取硬盘ID
private void Button14_Click(object sender, System.EventArgs e)
{
String HDid;
ManagementClass cimobject = new ManagementClass("Win32_DiskDrive");
ManagementObjectCollection moc = cimobject.GetInstances();
foreach(ManagementObject mo in moc)
{
HDid = (string)mo.Properties["Model"].Value;
Response.Write(HDid);
}
}
#endregion #region 15.获取本机的用户列表
private void Button15_Click(object sender, System.EventArgs e)
{
SelectQuery query = new SelectQuery("SELECT * FROM Win32_UserAccount");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach(ManagementObject os in searcher.Get())
{
Response.Write(os["Name"]);
}
}
#endregion
}
C# 查询Windows Service 信息 ,所在目录 启动状态的更多相关文章
- .Net C# Windows Service于server无法启动,错误 193:0xc1
1.情况说明:的近期发展windows维修,当地win7系统正常.把server安装会失败. 图中的引导失败的例子.: 解决方法:执行->输入:eventvwr.msc 打开你的事件查看器 ...
- C#中级-Windows Service程序安装注意事项
一.前言 这周除了改写一些识别算法外,继续我的Socket服务编写.服务器端的Socket服务是以Windows Service的形式运行的. 在我完成Windows Service编写后,启动服务时 ...
- Windows Service 学习系列(二):C# windows服务:安装、卸载、启动和停止Windows Service几种方式
一.通过InstallUtil.exe安装.卸载.启动.停止Windows Service 方法一 1.以管理员身份运行cmd 2.安装windows服务 切换cd C:\Windows\Micros ...
- C#Windows Service服务程序的安装/卸载、启动/停止 桌面客户端管理程序设计
C#Windows Service服务程序的安装/卸载.启动/停止 桌面客户端管理程序设计 关于Windows Service程序的安装与卸载如果每次使用命令行操作,那简直要奔溃了,太麻烦而且还容易出 ...
- war包部署在tomcat下,使用windows service服务方式启动tomcat服务器,在包含调用dll的模块,报dll找不到问题的解决办法
问题描述: 开发了一个需要调用dll的java web程序,在idea开发环境下运行调试没问题,可以正常运行,在tomcat/bin下,运行批处理startup.bat,启动tomcat服务器,也可以 ...
- Windows批处理以服务的方式启动解决思路(ShadowsockR注册成Windows Service)
我以ShadowsockR的server启动来解释: 由于这东西是python,如果要启动,可以写一个批处理(python.exe server.py)来启动,但是我观察发现启动的时候是附带pytho ...
- Windows服务器Pyton辅助运维--01.自动Copy文件(文件夹)到远程服务器所在目录
Windows服务器Pyton辅助运维 01.自动Copy文件(文件夹)到远程服务器所在目录 开发环境: u Web服务器: Windows Server 2008 R2 SP1 IIS 7.5 u ...
- windows Service启动带有管理员权限的GUI进程
事情是这样的,公司的产品有个守护进程(windows Service)需要启动产品的主程序exe,让主程序它运行为管理员权限(因为主程序会加载一个插件,插件中有列出端口监听的功能,需要由端口查找到进程 ...
- 如何在HPUX的终端提示符前显示当前登录用户信息和所在目录
修改/etc/default/profile文件,在最后加上如下内容: case $LOGNAME in 'root') PS1="$LOGNAME@$(hostname): ...
随机推荐
- EntityFramework 4使用存储过程分页
CREATE PROC usp_OrgPage_SQL @pageIndex INT, @pageSize INT, @totalCount INT OUTPUT AS BEGIN SET @tota ...
- PreparedStatement和Statment
使用Statment安全性差,存在SQL注入隐患 public static void main(String[] args) { Connection conn=null; Statement st ...
- Flex4 自定义分页组件
自己写的Flex4分页组件,去伪存真,只实现基本的分页功能,数据过滤神马的都不应该是分页组件干的活,有呆毛才有真相: [源代码下载] Flex自从转手给Apache后人气急跌,本人也很捉鸡,尽管Apa ...
- c# 读取XML数据
1.首先调用接口,要有一个post数据到指定url并返回数据的函数: protected string PostXmlToUrl(string url, string postData) { stri ...
- NTP服务器地址及IP
yum install ntp */20 * * * * /usr/sbin/ntpdate 61.172.254.29 210.72.145.44 (国家授时中心服务器IP地址)133.100.11 ...
- Java基础——IO流
今天刚刚看完java的io流操作,把主要的脉络看了一遍,不能保证以后使用时都能得心应手,但是最起码用到时知道有这么一个功能可以实现,下面对学习进行一下简单的总结: IO流主要用于硬板.内存.键盘等处理 ...
- 华为OJ平台——超长正整数相加
题目描述: 请设计一个算法完成两个超长正整数的加法. 输入 输入两个字符串数字 输出 输出相加后的结果,string型 样例输入 99999999999999999999999999999999999 ...
- jquery学习记录
1.选择器实例 语法 描述 $(this) 当前 HTML 元素 $("p") 所有 <p> 元素 $("p.intro") 所有 class=&q ...
- Ossim主要功能实战
Ossim主要功能实战 OSSIM通过将开源产品进行集成,从而提供一种能够实现安全监控功能的基础平台将Nagiso,Ntop,Snort,Nmap等开源工具集成在一起提供综合的安全保护功能,而不必在各 ...
- ios9和ios10的新特性
昨天面试了一个做ios开发的公司,其中面试官问我最新的ios系统版本是多少,以及它的特性是什么?由于自己是初学者,所以对这些没有关注过.今天特地搜索了一下关于ios9和ios10的新特性,并整理了一下 ...