读书人

C#获取服务详细信息ExecutionEngineEx

发布时间: 2012-03-26 15:46:55 作者: rapoo

C#获取服务详细信息ExecutionEngineException异常
我在C#中调用Windows API获取服务详细信息时引发了ExecutionEngineException异常,但调试时发现已经得到了正确的信息
请高手帮帮忙,看看问题出在哪
代码如下:

[StructLayout(LayoutKind.Sequential)]
public struct QUERY_SERVICE_CONFIG
{
public int dwServiceType;
public int dwStartType;
public int dwErrorControl;
public string lpBinaryPathName;
public string lpLoadOrderGroup;
public int dwTagId;
public string lpDependencies;
public string lpServiceStartName;
public string lpDisplayName;
}
[StructLayout(LayoutKind.Sequential)]
public struct SERVICE_DESCRIPTION
{
public string lpDescription;
}

//连接服务控制管理器
[DllImport("Advapi32.dll")]
extern static int OpenSCManager(string lpMachineName, string lpDatabaseName, int dwDesiredAccess);
//打开服务
[DllImport("Advapi32.dll")]
extern static int OpenService(int hSCManager, string lpServiceName, int dwDesiredAccess);
//获取服务配置
[DllImport("Advapi32.dll")]
extern static bool QueryServiceConfig(int hService,out QUERY_SERVICE_CONFIG QueryServiceConfig, int cbBufSize, out int

pcbBytesNeeded);
//获取服务描述
[DllImport("Advapi32.dll")]
extern static bool QueryServiceConfig2(int hService, int dwInfoLevel, out SERVICE_DESCRIPTION ServiceDescription, int

cbBufSize, out int pcbBytesNeeded);
//获取错误代码
[DllImport("Kernel32.dll")]
extern static int GetLastError();

QUERY_SERVICE_CONFIG qsc = new QUERY_SERVICE_CONFIG(String serviceName);
SERVICE_DESCRIPTION sd = new SERVICE_DESCRIPTION();

public void GetLocalServiceAttribute()
{
int hSCManager = OpenSCManager(null, null, 0xF003F);////SC_MANAGER_ALL_ACCESS (0xF003F)
if (hSCManager != 0)
{
int hService = OpenService(hSCManager, serviceName, 0xF01FF);////SERVICE_ALL_ACCESS (0xF01FF)
if (hService != 0)
{
int dwError=0, cbBufSize=0, dwBytesNeeded=0;

if (!QueryServiceConfig(hService, out qsc, 0, out dwBytesNeeded))
{
dwError = GetLastError();
if (dwError == 122)
{
cbBufSize = dwBytesNeeded;
}
else
{
MessageBox.Show("Query Service: " + serviceName + "'s Config Failed!");
}
}
if (!QueryServiceConfig(hService, out qsc, cbBufSize, out dwBytesNeeded))
{
MessageBox.Show("Query Service: " + serviceName + "'s Config Failed!");
}

if (!QueryServiceConfig2(hService, 1, out sd, 0, out dwBytesNeeded))
{
//第二个参数:dwInfoLevel:1==SERVICE_CONFIG_DESCRIPTION
dwError = GetLastError();
if (dwError == 122)
{
cbBufSize = dwBytesNeeded;


if (!QueryServiceConfig2(hService, 1, out sd, cbBufSize, out dwBytesNeeded))
{
MessageBox.Show("Query Service: " + serviceName + "'s Description Failed!");
}
}
else
{
MessageBox.Show("Query Service: " + serviceName + "'s Description Failed!");
}
}
}
else
{
MessageBox.Show("OpenService " + serviceName + " Failed!");
}
}
else
{
MessageBox.Show("OpenSCManager Failed!");
}
}
}



[解决办法]
哪一句代码引发了ExecutionEngineException异常?断点设置,调试一下。定位错误位置先。
[解决办法]
没有详细的看你的代码
如果.net 下控制service ,可以用servicecontroller,更简单些
如果用win32 api ,要考虑的东西比较多,容易出错

读书人网 >C#

热点推荐