public static void Close() { if (_driver != null) { uint refCount = 0; _driver.DeviceIOControl(Ring0.IOCTL_OLS_GET_REFCOUNT, null, ref refCount); _driver.Close(); if (refCount <= 1) { _driver.Delete(); } _driver = 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; } }