public bool Install(string path, out string errorMessage) { IntPtr manager = AdvApi32.OpenSCManager(null, null, AdvApi32.SC_MANAGER_ACCESS_MASK.SC_MANAGER_ALL_ACCESS); if (manager == IntPtr.Zero) { errorMessage = "OpenSCManager returned zero."; return(false); } IntPtr service = AdvApi32.CreateService(manager, _id, _id, AdvApi32.SERVICE_ACCESS_MASK.SERVICE_ALL_ACCESS, AdvApi32.SERVICE_TYPE.SERVICE_KERNEL_DRIVER, AdvApi32.SERVICE_START.SERVICE_DEMAND_START, AdvApi32.SERVICE_ERROR.SERVICE_ERROR_NORMAL, path, null, null, null, null, null); if (service == IntPtr.Zero) { if (Marshal.GetHRForLastWin32Error() == Kernel32.ERROR_SERVICE_EXISTS) { errorMessage = "Service already exists"; return(false); } errorMessage = "CreateService returned the error: " + Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()).Message; AdvApi32.CloseServiceHandle(manager); return(false); } if (!AdvApi32.StartService(service, 0, null)) { if (Marshal.GetHRForLastWin32Error() != Kernel32.ERROR_SERVICE_ALREADY_RUNNING) { errorMessage = "StartService returned the error: " + Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()).Message; AdvApi32.CloseServiceHandle(service); AdvApi32.CloseServiceHandle(manager); return(false); } } AdvApi32.CloseServiceHandle(service); AdvApi32.CloseServiceHandle(manager); #if !NETSTANDARD2_0 try { // restrict the driver access to system (SY) and builtin admins (BA) // TODO: replace with a call to IoCreateDeviceSecure in the driver FileInfo fileInfo = new FileInfo(@"\\.\" + _id); FileSecurity fileSecurity = FileSystemAclExtensions.GetAccessControl(fileInfo); fileSecurity.SetSecurityDescriptorSddlForm("O:BAG:SYD:(A;;FA;;;SY)(A;;FA;;;BA)"); FileSystemAclExtensions.SetAccessControl(fileInfo, fileSecurity); } catch { } #endif errorMessage = null; return(true); }