日期:2014-05-18  浏览次数:20873 次

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();