public static void RegistryHooksTimeout() { string subKey = @"Control Panel\Desktop"; RegistryKey mKey = Registry.CurrentUser.CreateSubKey(subKey); mKey?.SetValue("LowLevelHooksTimeout", 10000); mKey?.Dispose(); subKey = @".DEFAULT\Control Panel\Desktop"; mKey = Registry.Users.CreateSubKey(subKey); mKey?.SetValue("LowLevelHooksTimeout", 10000); mKey?.Dispose(); }
public static bool ModifyCurrentUserRegistryKey(string registerPath, string exeName, string value) { RegistryKey currentUserKey = null; RegistryKey subKey = null; try { currentUserKey = Registry.CurrentUser; subKey = GetSubKey(currentUserKey, registerPath); if (subKey != null) { subKey.SetValue(exeName, value, RegistryValueKind.DWord); subKey.Close(); subKey.Dispose(); } } catch (Exception e) { subKey?.Close(); subKey?.Dispose(); return(false); } currentUserKey?.Close(); currentUserKey?.Dispose(); return(true); }
public static bool DeleteCurrentUserRegistryKey(string registerPath, string key) { RegistryKey currentUserKey = null; RegistryKey subKey = null; try { currentUserKey = Registry.CurrentUser; subKey = GetSubKey(currentUserKey, registerPath); if (subKey != null) { subKey.DeleteValue(key, false); subKey.Close(); subKey.Dispose(); } } catch (Exception e) { subKey?.Close(); subKey?.Dispose(); return(false); } currentUserKey?.Close(); currentUserKey?.Dispose(); return(true); }
/// <summary> /// Sets the registry string. /// </summary> /// <param name="key">The key.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <param name="defaultValue">The default value.</param> private static void SetRegistryString(string key, string name, string value, string defaultValue) { using (RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)) { RegistryKey subkey = null; try { subkey = baseKey.OpenSubKey(key, true) ?? baseKey.CreateSubKey(key); if (subkey != null) { if (string.IsNullOrEmpty(value)) { value = defaultValue; } subkey.SetValue(name, value); } } finally { subkey?.Dispose( ); } } }
/// <summary> /// Returns a key from a registry key path /// </summary> /// <param name="fullPath">The full path of the key</param> /// <param name="registryView">The view to use when opening the key</param> /// <param name="writable">True if the key should be writable</param> /// <returns>The registry key</returns> public static RegistryKey?GetKeyFromFullPath(string fullPath, RegistryView registryView, bool writable = false) { // Split the keys string[] keys = NormalizePath(fullPath).Split(KeySeparatorCharacter); RegistryKey?key = null; try { // Open the base key key = RegistryKey.OpenBaseKey(GetHiveFromName(keys[0]), registryView); // If the path is only the base key, return it if (keys.Length == 1) { return(key); } // Get the sub key RegistryKey?returnValue = key.OpenSubKey(String.Join(KeySeparatorCharacter.ToString(), keys.Skip(1)), writable); // Return the sub key return(returnValue); } finally { // Dispose the base key key?.Dispose(); } }
private static bool IsCredentialGuardEnabledAtLocation(string registryKey) { // Guard if (string.IsNullOrEmpty(registryKey)) { return(false); } bool result = false; RegistryKey rk = null; // Use this pattern instead of nesting a try with using statement try { rk = Registry.LocalMachine.OpenSubKey(registryKey); if (rk != null) { object v = rk.GetValue("LsaCfgFlags"); int intVal = Convert.ToInt32(v); // If conversion fails, we go to the catch block result = (intVal == 1 || intVal == 2); } } catch { /* Nothing to do */ } finally { rk?.Dispose(); } return(result); }
private static RegistryKey GetKey() { RegistryKey key = null; RegistryKey key2 = null; try { using (key = Registry.CurrentUser.OpenSubKey("Software", true) ?? Registry.CurrentUser.CreateSubKey("Software", RegistryKeyPermissionCheck.ReadWriteSubTree)) { using (key2 = key.OpenSubKey("OCTGN", true) ?? key.CreateSubKey("OCTGN", RegistryKeyPermissionCheck.ReadWriteSubTree)) { var key3 = key2.OpenSubKey(KeyName, true) ?? key2.CreateSubKey(KeyName, RegistryKeyPermissionCheck.ReadWriteSubTree); return(key3); } } } catch { key?.Dispose(); key2?.Dispose(); throw; } }
public void Dispose() { _defaultConnectionKey?.Dispose(); _inventory?.Dispose(); _users?.Dispose(); _registryKey?.Dispose(); }
public static void RegistryDisableTaskMgr(int value) { string subKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"; RegistryKey mKey = Registry.CurrentUser.CreateSubKey(subKey); mKey?.SetValue("DisableTaskMgr", value); mKey?.Dispose(); }
public void Dispose() { if (!_disposed) { _key?.Dispose(); } _disposed = true; }
private static IEnumerable <Session> GetLoggedOnUsersRegistry(Computer computer) { if (Options.Instance.NoRegistryLoggedOn) { yield break; } RegistryKey key = null; IEnumerable <string> filteredKeys; try { //Try to open the remote base key key = RegistryKey.OpenRemoteBaseKey(RegistryHive.Users, computer.APIName); //Find subkeys where the regex matches filteredKeys = key.GetSubKeyNames().Where(subkey => SidRegex.IsMatch(subkey)); } catch (Exception e) { if (Options.Instance.DumpComputerStatus) { OutputTasks.AddComputerStatus(new ComputerStatus { ComputerName = computer.DisplayName, Status = e.Message, Task = "RegistryLoggedOn" }); } yield break; } finally { //Ensure we dispose of the registry key key?.Dispose(); } foreach (var sid in filteredKeys) { yield return(new Session { ComputerId = computer.ObjectIdentifier, UserId = sid }); } if (Options.Instance.DumpComputerStatus) { OutputTasks.AddComputerStatus(new ComputerStatus { ComputerName = computer.DisplayName, Status = "Success", Task = "RegistryLoggedOn" }); } }
/// <summary> /// 打开系统默认浏览器(用户自己设置了默认浏览器) /// </summary> /// <param name="url"></param> public bool OpenDefaultBrowser(string url) { RegistryKey key = null; try { // 方法1 //从注册表中读取默认浏览器可执行文件路径 key = Registry.ClassesRoot.OpenSubKey(@"http\shell\open\command\"); if (key != null) { string s = key.GetValue("").ToString(); //s就是你的默认浏览器,不过后面带了参数,把它截去,不过需要注意的是:不同的浏览器后面的参数不一样! //"D:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -- "%1" var lastIndex = s.IndexOf(".exe", StringComparison.Ordinal); if (lastIndex == -1) { lastIndex = s.IndexOf(".EXE", StringComparison.Ordinal); } var path = s.Substring(1, lastIndex + 3); var result = Process.Start(path, url); if (result == null) { // 方法2 // 调用系统默认的浏览器 var result1 = Process.Start("explorer.exe", url); if (result1 == null) { // 方法3 Process.Start(url); } } } else { // 方法2 // 调用系统默认的浏览器 var result1 = Process.Start("explorer.exe", url); if (result1 == null) { // 方法3 Process.Start(url); } } return(true); } catch (Exception error) { MessageBox.Show("无法使用默认浏览器:\n" + error.Message); return(false); } finally { key?.Dispose(); } }
public void Dispose() { _msMachineKey?.Dispose(); _vsPre2017MachineKey?.Dispose(); foreach (var vsPost2015DataItem in _vsPost2015Data) { vsPost2015DataItem.Dispose(); } }
public void Close() { lock (this) { if (key != null) { cache.TryRemove(key.GetHashCode(), out _); key.Dispose(); key = null; } } }
public void RegistryKeyGetValueMultiStringDoesNotDiscardZeroLengthStrings() { string[] before = new string[] { "", "Hello", "", "World", "" }; string[] after; RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(_getValueBug); key.SetValue("Test", before); after = key.GetValue("Test") as string[]; key.Dispose(); Assert.Equal(before, after); }
public static string GetMSNInstallPath(string version) { string installPath = null; string keyName = GetKeyName(version); RegistryKey regKey = GetRegistryKey(keyName, RegistryHive.LocalMachine); if (regKey != null) { installPath = (string)regKey.GetValue("InstallPath"); // It might be that InstallPath is null as the previous version has been uninstalled or re-installed only for the current user. if (string.IsNullOrEmpty(installPath)) { regKey.Dispose(); regKey = null; } } if (regKey == null) { regKey = GetRegistryKey(keyName, RegistryHive.CurrentUser); } if (regKey == null) { throw new IOException("Unable to determine installed version."); } installPath = (string)regKey.GetValue("InstallPath"); if (string.IsNullOrEmpty(installPath)) { throw new IOException("InstallPath is null."); } regKey.Dispose(); regKey = null; return(installPath); }
public Task <bool> Check() { RegistryKey runKey = null; try { runKey = OpenRegKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); if (runKey == null) { logger.Error(@"Cannot find HKCU\Software\Microsoft\Windows\CurrentVersion\Run"); return(Task.FromResult(false)); } string[] runList = runKey.GetValueNames(); foreach (string item in runList) { if (item.Equals(Key, StringComparison.OrdinalIgnoreCase)) { return(Task.FromResult(true)); } //else if (item.Equals("Shadowsocks", StringComparison.OrdinalIgnoreCase)) // Compatibility with older versions //{ // string value = Convert.ToString(runKey.GetValue(item)); // if (ExecutablePath.Equals(value, StringComparison.OrdinalIgnoreCase)) // { // runKey.DeleteValue(item); // runKey.SetValue(Key, ExecutablePath); // return true; // } //} } return(Task.FromResult(false)); } catch (Exception e) { logger.Error(e); return(Task.FromResult(false)); } finally { if (runKey != null) { try { runKey.Close(); runKey.Dispose(); } catch (Exception e) { logger.Error(e); } } } }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { baseRegistryKey.Dispose(); } disposedValue = true; } }
public static List <AppData> ReadApps() { string registryKeyString = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"; string registryKeyString32 = @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"; Dictionary <string, AppData> appsList = new Dictionary <string, AppData>(); RegistryKey registryKey = null; try { registryKey = Registry.LocalMachine.OpenSubKey(registryKeyString); if (registryKey != null) { appsList = readAppsSubKey(registryKey); } registryKey = Registry.CurrentUser.OpenSubKey(registryKeyString); if (registryKey != null) { appsList = combineLists(appsList, readAppsSubKey(registryKey)); } registryKey = Registry.LocalMachine.OpenSubKey(registryKeyString32); if (registryKey != null) { appsList = combineLists(appsList, readAppsSubKey(registryKey)); } registryKey = Registry.CurrentUser.OpenSubKey(registryKeyString32); if (registryKey != null) { appsList = combineLists(appsList, readAppsSubKey(registryKey)); } // TODO(DB): Add a check to make sure possible duplicates from HKEY_CURRENT_USER are not added to the returned list. } catch (Exception Ex) { Console.WriteLine(Ex.ToString()); return(appsList.Values.ToList()); } finally { if (registryKey != null) { registryKey.Dispose(); } } return(appsList.Values.ToList()); }
public static void createSoftwareRegistryKeys() { RegistryKey SoftwareKey = Registry.CurrentUser.OpenSubKey("Software", true); RegistryKey SoftwareVendorKey = null; RegistryKey SoftwareNameKey = null; try { SoftwareVendorKey = Registry.CurrentUser.OpenSubKey("Software\\QXS", true); if (SoftwareVendorKey == null) { SoftwareKey.CreateSubKey(SoftwareVendor); SoftwareVendorKey = Registry.CurrentUser.OpenSubKey("Software\\" + SoftwareVendor, true); } if (SoftwareVendorKey == null) { throw new Exception("FAILED TO CREATE THE REGISTRY KEY: HKEY_CURRENT_USER\\" + "Software\\" + SoftwareVendor); } SoftwareNameKey = Registry.CurrentUser.OpenSubKey("Software\\" + SoftwareVendor + "\\" + SoftwareName, true); if (SoftwareNameKey == null) { SoftwareVendorKey.CreateSubKey(SoftwareName); SoftwareNameKey = Registry.CurrentUser.OpenSubKey("Software\\" + SoftwareVendor + "\\" + SoftwareName, false); } if (SoftwareNameKey == null) { throw new Exception("FAILED TO CREATE THE REGISTRY KEY: HKEY_CURRENT_USER\\" + "Software\\" + SoftwareVendor + "\\" + SoftwareName); } } finally { if (SoftwareNameKey != null) { SoftwareVendorKey.Close(); SoftwareNameKey.Dispose(); } if (SoftwareVendorKey != null) { SoftwareVendorKey.Close(); SoftwareVendorKey.Dispose(); } if (SoftwareKey != null) { SoftwareKey.Close(); SoftwareVendorKey.Dispose(); } } }
public void TearDown() { TeProjectSettings.Release(); FwRegistrySettings.Release(); ReflectionHelper.CallStaticMethod("FwResources.dll", "SIL.FieldWorks.Resources.ResourceHelper", "ShutdownHelper"); if (m_RegistryKey != null) { m_RegistryKey.Dispose(); } m_RegistryKey = null; }
/// <summary> /// Probe the startup /// </summary> /// <param name="pm">The method to use</param> public void ProbeStart(ProbeMethod pm) { if (pm == ProbeMethod.StartUpFolder) //Probe starup folder { var suFolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup); //Get the path of the startup folder var linkFile = suFolder + "\\" + "client.lnk"; //Be creative if you want to get away with it :) if (!File.Exists(linkFile)) { CreateShortcut(linkFile, Application.ExecutablePath); //Create the new link file } } else if (pm == ProbeMethod.Registry) //Probe the registry { if (!IsAdmin()) //Check if client is admin { //Report error to the server _reportHelper.ReportError(ErrorType.ADMIN_REQUIRED, "Failed to probe registry", "R.A.T is not running as admin! You can try to bypass the uac or use the startup folder method!"); return; //Return } RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\run", true); //Get the usual registry key if (key.GetValue("tut_client") != null) { key.DeleteValue("tut_client", false); //Check and remove value } key.SetValue("tut_client", Application.ExecutablePath); //Add the new value //Close and dispose the key key.Close(); key.Dispose(); key = null; } else if (pm == ProbeMethod.TaskScheduler) //Probe TaskScheduler { if (!IsAdmin()) //Check if client is admin { //Report error to the server _reportHelper.ReportError(ErrorType.ADMIN_REQUIRED, "Failed to probe Task Scheduler", "R.A.T is not running as admin! You can try to bypass the uac or use the startup folder method!"); return; //Return } Process deltask = new Process(); //Delete previous task Process addtask = new Process(); //Create the new task deltask.StartInfo.FileName = "cmd.exe"; //Execute the cmd deltask.StartInfo.Arguments = "/c schtasks /Delete tut_client /F"; //Set tasksch command deltask.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //Hidden process deltask.Start(); //Delete the task deltask.WaitForExit(); //Wait for it to finish //Console.WriteLine("Delete Task Completed"); addtask.StartInfo.FileName = "cmd.exe"; //Execute the cmd addtask.StartInfo.Arguments = "/c schtasks /Create /tn tut_client /tr \"" + Application.ExecutablePath + "\" /sc ONLOGON /rl HIGHEST"; //Set tasksch command addtask.Start(); //Add the new task addtask.WaitForExit(); //Wait for it to finish //Console.WriteLine("Task created successfully!"); } }
private static RegistryKey GetRegistryKey(string keyname) { RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); RegistryKey key = baseKey.OpenSubKey(keyname); if (key == null) { baseKey.Dispose(); baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default); key = baseKey.OpenSubKey(keyname); } if (key == null) { baseKey.Dispose(); baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); key = baseKey.OpenSubKey(keyname); } baseKey.Dispose(); return(key); }
public void Dispose() { if (!_disposed) { _disposed = true; _eventHandle.Dispose(); if (_key != null) { _key.Dispose(); } } }
public static BasicReturnInfo Check() { RegistryKey runKey = null; try { runKey = Utils.OpenRegKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true).Instance as RegistryKey; if (runKey == null) { // Logging.Error(@"Cannot find HKCU\Software\Microsoft\Windows\CurrentVersion\Run"); return(BasicReturnInfo.Create(false, 0x0040003)); } string[] runList = runKey.GetValueNames(); foreach (string item in runList) { if (item.Equals(Key, StringComparison.OrdinalIgnoreCase)) { return(BasicReturnInfo.OK()); } else if (item.Equals("SimpleSrun4K", StringComparison.OrdinalIgnoreCase)) // Compatibility with older versions { string value = Convert.ToString(runKey.GetValue(item)); if (ExecutablePath.Equals(value, StringComparison.OrdinalIgnoreCase)) { runKey.DeleteValue(item); runKey.SetValue(Key, ExecutablePath); return(BasicReturnInfo.OK()); } } } return(BasicReturnInfo.Create(false, 0x0040004)); } catch (Exception e) { // Logging.LogUsefulException(e); return(BasicReturnInfo.Create(false, 0x0040005)); } finally { if (runKey != null) { try { runKey.Close(); runKey.Dispose(); } catch (Exception e) { //Logging.LogUsefulException(e); } } } }
private void SetDate() { CreateKey(); RegistryKey expr_0B = Registry.CurrentUser; RegistryKey expr_17 = expr_0B.OpenSubKey("SOFTWARE\\DevExpress\\Components", true); expr_17.GetValue("LastAboutShowedTime"); string value = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"); expr_17.SetValue("LastAboutShowedTime", value); expr_0B.Dispose(); }
/// <summary> /// Adds the application to Windows autostart /// </summary> public static void AddAutoStart() { try { RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); registryKey.SetValue("AutoDarkMode", '\u0022' + Extensions.ExecutionPath + '\u0022'); registryKey.Dispose(); } catch (Exception ex) { Logger.Error(ex, "could not add AutoDarkModeSvc to autostart"); } }
/// <summary> /// Test if HKEY_CLASSES_ROOT\mailto\shell\open\command\ has value not set to C:\windows\system32\ /// </summary> /// <returns></returns> public static bool TestOpenCommand() { bool bReturn = false; string subKeyPath = @"mailto\shell\open\command\"; try { RegistryKey key = Registry.ClassesRoot.OpenSubKey(subKeyPath); if (key != null) { object objValue = key.GetValue(""); if (objValue != null) { if (key.GetValueKind("") != RegistryValueKind.String) { bReturn = false; MessageBox.Show("Default mailto command value is not a string type"); } else { string strValue = Convert.ToString(objValue); if (strValue != null) { if (strValue.IndexOf(@"C:\windows\system", StringComparison.OrdinalIgnoreCase) >= 0) { bReturn = false; } else { bReturn = true; } } MessageBox.Show("Default mailto command value is " + strValue); } } else { MessageBox.Show("Default command value does not exist"); bReturn = false; } key.Close(); key.Dispose(); key = null; } else { MessageBox.Show("HKEY_CLASSES_ROOT\\mailto\\shell\\open\\command\\\ndoes not exist"); } } catch { } return(bReturn); }
private void CreateKey() { RegistryKey currentUser = Registry.CurrentUser; if (currentUser.OpenSubKey("SOFTWARE\\DevExpress\\Components", true) == null) { RegistryKey expr_1F = currentUser.CreateSubKey("SOFTWARE\\DevExpress\\Components"); expr_1F.CreateSubKey("LastAboutShowedTime").SetValue("LastAboutShowedTime", DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")); expr_1F.CreateSubKey("DisableSmartTag").SetValue("LastAboutShowedTime", false); expr_1F.CreateSubKey("SmartTagWidth").SetValue("LastAboutShowedTime", 350); } currentUser.Dispose(); }
/// <summary> /// Removes the application from Windows autostart /// </summary> public static void RemoveAutoStart() { try { RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); registryKey.DeleteValue("AutoDarkMode", false); registryKey.Dispose(); } catch (Exception ex) { Logger.Error(ex, "could not remove AutoDarkModeSvc from autostart"); } }