public static void Close() { if (_driver != null) { uint refCount = 0; _driver.DeviceIOControl(Interop.Ring0.IOCTL_OLS_GET_REFCOUNT, null, ref refCount); _driver.Close(); if (refCount <= 1) { _driver.Delete(); } _driver = null; } if (_isaBusMutex != null) { _isaBusMutex.Close(); _isaBusMutex = null; } // try to delete temporary driver file again if failed during open if (_fileName != null && File.Exists(_fileName)) { try { File.Delete(_fileName); _fileName = null; } catch (IOException) { } catch (UnauthorizedAccessException) { } } }
public static void Open() { if (_driver != null) { return; } // clear the current report Report.Length = 0; _driver = new KernelDriver("WinRing0_1_2_0"); _driver.Open(); if (!_driver.IsOpen) { // driver is not loaded, try to install and open _fileName = GetTempFileName(); if (_fileName != null && ExtractDriver(_fileName)) { if (_driver.Install(_fileName, out string installError)) { _driver.Open(); if (!_driver.IsOpen) { _driver.Delete(); Report.AppendLine("Status: Opening driver failed after install"); } } else { string errorFirstInstall = installError; // install failed, try to delete and reinstall _driver.Delete(); // wait a short moment to give the OS a chance to remove the driver Thread.Sleep(2000); if (_driver.Install(_fileName, out string errorSecondInstall)) { _driver.Open(); if (!_driver.IsOpen) { _driver.Delete(); Report.AppendLine("Status: Opening driver failed after reinstall"); } } else { Report.AppendLine("Status: Installing driver \"" + _fileName + "\" failed" + (File.Exists(_fileName) ? " and file exists" : string.Empty)); Report.AppendLine("First Exception: " + errorFirstInstall); Report.AppendLine("Second Exception: " + errorSecondInstall); } } } else { Report.AppendLine("Status: Extracting driver failed"); } try { // try to delete the driver file if (File.Exists(_fileName) && _fileName != null) { File.Delete(_fileName); } _fileName = null; } catch (IOException) { } catch (UnauthorizedAccessException) { } } if (!_driver.IsOpen) { _driver = null; } string mutexName = "Global\\Access_ISABUS.HTP.Method"; try { #if NETSTANDARD2_0 _isaBusMutex = new Mutex(false, mutexName); #else //mutex permissions set to everyone to allow other software to access the hardware //otherwise other monitoring software cant access var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); _isaBusMutex = new Mutex(false, mutexName, out _, securitySettings); #endif } catch (UnauthorizedAccessException) { try { #if NETSTANDARD2_0 _isaBusMutex = Mutex.OpenExisting(mutexName); #else _isaBusMutex = Mutex.OpenExisting(mutexName, MutexRights.Synchronize); #endif } catch { } } }