public void SetServiceDescription(string serviceName, string description) { IntPtr service = IntPtr.Zero; try { ServiceWin32Api.SERVICE_DESCRIPTION desc = new ServiceWin32Api.SERVICE_DESCRIPTION { lpDescription = description }; // Open the service service = OpenService(serviceName, ServiceWin32Api.ServiceAccessRights.SERVICE_CHANGE_CONFIG); bool ok = ServiceWin32Api.ChangeServiceConfig2( service, (int)ServiceWin32Api.ServiceConfig2InfoLevel.SERVICE_CONFIG_DESCRIPTION, ref desc); // Check that the change occurred if (!ok) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to change the Service configuration."); } } finally { if (service != IntPtr.Zero) { ServiceWin32Api.CloseServiceHandle(service); } } }
public string GetServiceDescription(string serviceName) { const int bufferSize = 1024 * 8; IntPtr service = IntPtr.Zero; IntPtr bufferPtr = IntPtr.Zero; try { // Open the service service = OpenService(serviceName, ServiceWin32Api.ServiceAccessRights.SERVICE_QUERY_CONFIG); int dwBytesNeeded = 0; // Allocate memory for struct bufferPtr = Marshal.AllocHGlobal(bufferSize); int queryResult = ServiceWin32Api.QueryServiceConfig2( service, ServiceWin32Api.ServiceConfig2InfoLevel.SERVICE_CONFIG_DESCRIPTION, bufferPtr, bufferSize, out dwBytesNeeded); if (queryResult == 0) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to query the Service configuration."); } // Cast the buffer to a SERVICE_DESCRIPTION struct ServiceWin32Api.SERVICE_DESCRIPTION desc = (ServiceWin32Api.SERVICE_DESCRIPTION)Marshal.PtrToStructure(bufferPtr, typeof(ServiceWin32Api.SERVICE_DESCRIPTION)); return(desc.lpDescription); } finally { // Clean up if (bufferPtr != IntPtr.Zero) { Marshal.FreeHGlobal(bufferPtr); } if (service != IntPtr.Zero) { ServiceWin32Api.CloseServiceHandle(service); } } }
/// <summary> /// Implements the Dispose(bool) pattern outlined by MSDN and enforced by FxCop. /// </summary> private void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { // Dispose managed resources here } // Unmanaged resources always need disposing if (_scManager != IntPtr.Zero) { ServiceWin32Api.CloseServiceHandle(_scManager); _scManager = IntPtr.Zero; } } disposed = true; }