public Boolean SetRegistryKey(RegistryKey registryPath, Boolean readOnly = true, Boolean isSafe = true) { _registryKey?.Close(); IsSafe = isSafe; IsReadOnly = readOnly; try { _registryKey = registryPath; return(true); } catch (Exception) { return(false); } }
public static string RegReadValue(string path, string name, string def) { RegistryKey regKey = null; try { regKey = Registry.CurrentUser.OpenSubKey(path, false); string value = regKey?.GetValue(name) as string; if (IsNullOrEmpty(value)) { return def; } else { return value; } } catch (Exception ex) { SaveLog(ex.Message, ex); } finally { regKey?.Close(); } return def; }
public void SetAutoRunValue() { RegistryKey regKey = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run\\"); regKey?.SetValue("MyApp", Assembly.GetExecutingAssembly().Location); regKey?.Close(); }
private void Read_Click(object sender, EventArgs e) { RegistryKey registryKey = null; RegistryKey subKey = null; try { //Инициализируем объект Registry для работы с веткой реестра CurrentUser registryKey = Registry.CurrentUser; //Идем к ключу и читаем данные с него subKey = registryKey.OpenSubKey(@"Software\TestFolder\Test1"); string value = subKey.GetValue("CurrentText") as string; //Помещаем данные в тексбок textBox2.Text = value; MessageBox.Show("Чтение выполнено!"); } catch (Exception exception) { MessageBox.Show(exception.Message); } finally { registryKey?.Close(); subKey?.Close(); } }
/// <summary> /// De-register the application to open with the browser. /// </summary> /// <param name="Hostname">The hostname for the Native Messaging Host application</param> public void Unregister(string Hostname) { if (OperatingSystem.IsWindows()) { string targetKeyPath = regHostnameKeyLocation + Hostname; RegistryKey?regKey = Registry.CurrentUser.OpenSubKey(targetKeyPath, true); if (regKey != null) { regKey.DeleteSubKey("", true); } regKey?.Close(); Log.LogMessage( "Unregistered host (" + Hostname + ") with browser " + BrowserName); } else { throw new NotImplementedException( "Registration removal not implemented on this platform."); } }
public static ILanguage GetLanguage() { ILanguage result = new EnglishLanguage(); try { var hkcu = Registry.CurrentUser; RegistryKey settingsBranch = hkcu.OpenSubKey("Software\\YarcheTextEditor", true); if (settingsBranch == null) { hkcu.CreateSubKey("Software\\YarcheTextEditor"); settingsBranch = hkcu.OpenSubKey("Software\\YarcheTextEditor", true); } var languageCode = settingsBranch.GetValue("Language", "en").ToString(); settingsBranch?.Close(); hkcu?.Close(); result = LanguageMethods.GetLanguage(languageCode); } catch (Exception ex) { Log.Instance.Error(1, ex.Message, "RegistryMethods"); } return(result); }
private static bool TryGetSteamPathWin32([NotNullWhen(true)] out string?path) { path = null; RegistryKey?softwareKey = null; try { string softwarePath = Environment.Is64BitProcess ? @"SOFTWARE\WOW6432Node" : "SOFTWARE"; softwareKey = Registry.LocalMachine.OpenSubKey(softwarePath, false); if (softwareKey is null) { return(false); } using var key = softwareKey.OpenSubKey(@"Valve\Steam"); var obj = key?.GetValue("InstallPath"); path = obj as string; if (string.IsNullOrEmpty(path)) { return(false); } return(Directory.Exists(path)); } catch { return(false); } finally { softwareKey?.Close(); } }
public static void RegWriteValue(string path, string name, string value) { RegistryKey regKey = null; try { regKey = Registry.CurrentUser.CreateSubKey(path); if (string.IsNullOrEmpty(value)) { regKey?.DeleteValue(name, false); } else { regKey?.SetValue(name, value); } } catch (Exception) { // ignored } finally { regKey?.Close(); } }
/// <summary>Get path to system default browser</summary> public static string GetSystemDefaultBrowser() { string name; RegistryKey regKey = null; try { var regDefault = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.htm\\UserChoice", false); var stringDefault = regDefault.GetValue("ProgId"); regKey = Registry.ClassesRoot.OpenSubKey($"{stringDefault}\\shell\\open\\command", false); name = regKey.GetValue(null).ToString().ToLower().Replace("" + (char)34, ""); if (!name.EndsWith("exe")) { name = name.Substring(0, name.LastIndexOf(".exe", StringComparison.Ordinal) + 4); } } catch { name = ""; } finally { regKey?.Close(); } return(name); }
public static bool Check() { try { RegistryKey runKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); string[] runList = runKey?.GetValueNames(); runKey?.Close(); if (runList == null || runList.Length == 0) { return(false); } foreach (string item in runList) { if (item.Equals(KEY_NAME)) { return(true); } } return(false); } catch (Exception e) { Logging.LogUsefulException(e); return(false); } }
public static string RegReadValue(string path, string name, string def) { RegistryKey regKey = null; try { regKey = Registry.CurrentUser.OpenSubKey(path, false); string value = regKey?.GetValue(name) as string; if (IsNullOrEmpty(value)) { return(def); } else { return(value); } } catch { } finally { regKey?.Close(); } return(def); }
private void AddConfigKey() { _key = Registry.CurrentUser.OpenSubKey(RegLoc, true); using (var ms = new MemoryStream()) { try { var formatter = new BinaryFormatter(); formatter.Serialize(ms, GetCurrentConfig()); var data = ms.ToArray(); _key?.SetValue("config", data, RegistryValueKind.Binary); } catch (System.Runtime.Serialization.SerializationException e) { Console.WriteLine(e.Message); } catch (System.UnauthorizedAccessException e) { Console.WriteLine(e.Message); } } _key?.Close(); }
public void clearChildItem(string path) { RegistryKey root = null; string[] names = null; try { root = getPath(path, false); if (root == null) { return; } names = root.GetSubKeyNames(); for (int i = 0; i < names.Length; ++i) { root.DeleteSubKeyTree(names[i]); } } catch (Exception) { //return ""; } root?.Close(); //try { // each(path, (name) => { // }); //} catch(Exception) { //} }
public void save(RegistryKey root, string key) { RegistryKey grid = root.CreateSubKey(key); grid?.SetValue("Splitter", GetSplitterWidth()); grid?.Close(); }
public static Dictionary <string, object> GetValues(RegistryHive hive, string path, string computer = "") { // returns all registry values under the specified path in the specified hive (HKLM/HKCU) RegistryKey?rootHive = null; RegistryKey?key = null; try { rootHive = RegistryKey.OpenRemoteBaseKey(hive, computer); key = rootHive.OpenSubKey(path, false) ?? throw new Exception("Key doesn't exist"); var valueNames = key.GetValueNames(); var keyValuePairs = valueNames.ToDictionary(name => name, key.GetValue); return(keyValuePairs); } catch { return(new Dictionary <string, object>()); } finally { key?.Close(); rootHive?.Close(); } }
private void Write_Click(object sender, EventArgs e) { RegistryKey registryKey = null; RegistryKey subKey = null; try { //Инициализируем объект Registry для работы с веткой реестра CurrentUser registryKey = Registry.CurrentUser; //CreateSubKey - создать по указанному пути ключ subKey = registryKey.CreateSubKey(@"Software\TestFolder\Test1"); //Запись значений в реестр subKey.SetValue("CurrentText", textBox1.Text); //если такое свойство уже есть - ОНО ПЕРЕЗАПИШЕТСЯ! MessageBox.Show($"Запись {textBox1.Text} создана в реестре"); } catch (Exception exception) { MessageBox.Show(exception.Message); } finally { registryKey?.Close(); subKey?.Close(); } }
/// <inheritdoc /> public T GetConfigEntry <T>(String entryName, String node = null) { if (entryName == null) { throw new ArgumentNullException(nameof(entryName)); } if (String.Empty.Equals(entryName)) { throw new ArgumentException("'entryName' parameter cannot be empty string."); } String subKey = runtimePath; if (!String.IsNullOrWhiteSpace(node)) { subKey = runtimePath + node; } using (RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, ComputerName, RegistryView.Default)) { RegistryKey root = key.OpenSubKey(subKey, false); Object value = root?.GetValue(entryName, FAKE_VALUE); root?.Close(); if (value == null || FAKE_VALUE.Equals(value)) { throw new FileNotFoundException(); } return((T)value); } }
public static void ReadOrCreateADALTokenCache() { //bTokenCacheDeserializeAttempted初始化为false if (!bTokenCacheDeserializeAttempted) { RegistryKey registryKey = null; myTokenCache = null; try { //CreateSubKey(String, RegistryKeyPermissionCheck) //Creates a new subkey or opens an existing subkey for write access, using the specified permission check option. //Software\\Microsoft\\MSDTools\\OAuthCache --The name or path of the subkey to create or open. This string is not case-sensitive. //RegistryKeyPermissionCheck //One of the enumeration values that specifies whether the key is opened for read or read / write access. registryKey = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\MSDTools\\OAuthCache", RegistryKeyPermissionCheck.ReadSubTree); byte[] array = (byte[])registryKey.GetValue("ADALTokenCache", new byte[1]); if (array.Length > 1) { myTokenCache = new TokenCache(array); } } catch (Exception ex) { Console.WriteLine("Cannot read/use ADAL token cache: " + ex.Message + " ReadOrCreateADALTokenCache"); myTokenCache = null; } registryKey?.Close(); bTokenCacheDeserializeAttempted = true; if (myTokenCache == null) { myTokenCache = new TokenCache(); } } }
/// <summary> /// Метод для получения пути к браузеру по умолчанию. /// </summary> /// <remarks>https://www.dreamincode.net/forums/blog/143/entry-2054-get-default-browser-more-in-c?__cf_chl_captcha_tk__=3dc39ae30437c8455a9fd1602b28d87d6027d775-1619811676-0-AS80dDoSpAyN3-ESBn2Slvc8iTlXrSD3aFP7RSfjcGGdqlvON6wHGP4PpSGPG-HaJRxdm4FOV8GxqWDH3IjwPr0a08blha_HqSp-bZjZsAFn52B8qqcGh3oRAqxBjNG36iXz2puSGbEntIGvLmOwVn5jZi1lt7MqLhlI8HBzmCgti-IDBXXNQVXsZuEkHmB4fhG_HL6mZU37bWFaVCsPfpQyCiQp9ygrTylWIIF7LpluKhE-Fk9a8sEGZeMqAB573pXlYXXmWm5g34m1JUQVoFP_L_DncHNFAQ2Q-F6G8E24phSyc_8XkHq0C0P3wudvBrQ6aTKNmc66HsGGXrgyJ1QueN8_Tym_ZtzlGa2i_-N0vkLMJF927BWfCOFi4z7t7YcS9CwIDTPb_FxAUMWBI5iC5-jwUqXxbRb5H1pOfrIoXgOO19XNIiNdYHLxd1BzEKk1OyRBtgYW5KwJN4s309CfTwEEr51UKQQX1epCgsW133SLikcfC9t2f8qpsLuJ6jUUsm2tiyapG43x8Kkm1glkUYT7JgwQ6yH9sS3FJDcr9RqZtYa8jvMfewJ1evstmIgPNUen6Tv0EQ_Ec6g9mMOSYk-uZ6iGq6eHLp1lfrmaxrdgTvLaW2-Sc-XyLUjjWiWGopoAmhd07px8ncbTjHOjikJqMvlCo1fvwNurrVE8pkhBvIDUxlFOhVPOcMNFlQ#/.</remarks> /// <returns>Путь к испоняемому файлу браузера.</returns> private string GetSystemDefaultBrowser() { string name; RegistryKey regKey = null; try { regKey = Registry.ClassesRoot.OpenSubKey("HTTP\\shell\\open\\command", false); name = regKey?.GetValue(null).ToString().ToLower().Replace(string.Empty + (char)34, string.Empty); if (name == null) { throw new LibraryInnerException("Не удалось найти запись о браузере по умолчанию."); } if (!name.EndsWith("exe")) { name = name.Substring(0, name.LastIndexOf(".exe", StringComparison.Ordinal) + 4); } } catch (Exception ex) { name = $"ERROR: An exception of type: {ex.GetType()} occurred in method: {ex.TargetSite} in the following module: {GetType()}"; } finally { regKey?.Close(); } return(name); }
public void SaveLastPage(string userName, int page) { RegistryKey masterKey = null; try { masterKey = Registry.CurrentUser.CreateSubKey(MASTER_REG_KEY); RegistryKey userKey = masterKey?.CreateSubKey($"{SAVED_USERS_SUB_KEY}\\{userName}"); if (userKey == null) { return; } userKey.SetValue("LastPage", page); } catch (Exception ex) { Trace.WriteError("Saving user info to registry failed", Trace.GetMethodName(), CLASSNAME, ex); } finally { masterKey?.Close(); } }
public List <SavedUser> GetAllSavedUsers(out String lastUser) { var result = new List <SavedUser>(); lastUser = ""; RegistryKey masterKey = null; try { masterKey = Registry.CurrentUser.OpenSubKey(MASTER_REG_KEY); if (masterKey != null) { lastUser = masterKey.GetValue("LastUser", "").ToString(); RegistryKey savedUsersKey = masterKey.OpenSubKey(SAVED_USERS_SUB_KEY); if (savedUsersKey != null) { result.AddRange(from name in savedUsersKey.GetSubKeyNames() select savedUsersKey.OpenSubKey(name) into userKey where userKey != null select new SavedUser(userKey.GetValue("UserName", "").ToString(), "", (int)userKey.GetValue("LastPage", -1))); } } } catch (Exception ex) { Trace.WriteError("Loading user info from registry failed", Trace.GetMethodName(), CLASSNAME, ex); } finally { masterKey?.Close(); } return(result); }
public static bool SetRegistryValue( string registryPath, string key, object value, RegistryValueKind type, RegistryKeyKind registryKind = RegistryKeyKind.HKEY_LOCAL_MACHINE) { RegistryKey registryKey = (RegistryKey)null; bool flag = true; try { switch (registryKind) { case RegistryKeyKind.HKEY_LOCAL_MACHINE: registryKey = Registry.LocalMachine.CreateSubKey(registryPath); break; case RegistryKeyKind.HKEY_CURRENT_USER: registryKey = Registry.CurrentUser.CreateSubKey(registryPath); break; } registryKey?.SetValue(key, value, type); } catch { Logger.Warning("Failed to set registry value at {0} for {1}:{2}", (object)registryPath, (object)key, value); flag = false; } finally { registryKey?.Close(); } return(flag); }
private void InstallAdministratorRegistry() { RegistryKey administratorKey = defaultKey?.CreateSubKey("runas", RegistryKeyPermissionCheck.ReadWriteSubTree); try { administratorKey?.SetValue("", runAsAdministratorNameTextBox.Text); } catch { // ignored } try { if (runAsAdministratorIconTextBox.Text != String.Empty) { administratorKey?.SetValue("icon", Path.Combine(IcoDirectory, @"Administrator\Administrator.ico")); } else { administratorKey?.DeleteValue("icon"); } } catch { // ignored } administratorKey?.Close(); }
public static bool RegReadValue(string path, string name, bool def) { RegistryKey regKey = null; try { regKey = Registry.CurrentUser.OpenSubKey(path, false); var valueobj = regKey?.GetValue(name); var value = valueobj as int?; if (!value.HasValue) { return(def); } else { return(value.Value == 1); } } catch { } finally { regKey?.Close(); } return(def); }
static bool TryGetSteamPathWin32(out string path) { RegistryKey softwareKey = null; try { string softwarePath = Environment.Is64BitProcess ? @"SOFTWARE\WOW6432Node" : "SOFTWARE"; softwareKey = Registry.LocalMachine.OpenSubKey(softwarePath, false); using (var key = softwareKey.OpenSubKey(@"Valve\Steam")) { var obj = key.GetValue("InstallPath"); path = obj as string; return(Directory.Exists(path)); } } catch { path = null; return(false); } finally { softwareKey?.Close(); } }
/// <summary> /// 开机自动启动 /// </summary> /// <param name="run"></param> /// <returns></returns> public static int SetAutoRun(bool run) { RegistryKey regKey = null; try { regKey = Registry.LocalMachine.CreateSubKey(autoRunRegPath); if (run) { string exePath = GetExePath(); regKey.SetValue(autoRunName, exePath); } else { regKey.DeleteValue(autoRunName, false); } } catch { } finally { regKey?.Close(); } return(0); }
public static bool Set(bool enabled) { RegistryKey runKey = null; try { var path = Application.ExecutablePath; runKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); Debug.Assert(runKey != null, "runKey != null"); runKey.SetValue(Key, path); if (!enabled) { runKey.DeleteValue(Key); } return(true); } catch (Exception e) { Trace.WriteLine(e.Message); return(false); } finally { runKey?.Close(); } }
public static void RegWriteValue(string path, string name, object value) { RegistryKey regKey = null; try { regKey = Registry.CurrentUser.CreateSubKey(path); if (IsNullOrEmpty(value.ToString())) { regKey?.DeleteValue(name, false); } else { regKey?.SetValue(name, value); } } catch (Exception ex) { SaveLog(ex.Message, ex); } finally { regKey?.Close(); } }
/// <summary> /// Checks if Google Chrome is installed /// </summary> /// <returns>True if its installed</returns> public static bool IsInstalled() { RegistryKey regKey = null; var installed = false; try { regKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome"); if (regKey != null) { if (GetChromeUserDir()) { installed = true; } else { Debug.WriteLine("Unable to determine Google Chrome profile directory."); } } } catch { installed = false; } finally { regKey?.Close(); } return(installed); }
private string GetSystemDefaultBrowserPath() { string name; RegistryKey regKey = null; try { regKey = Registry.ClassesRoot.OpenSubKey("HTTP\\shell\\open\\command", false); // Remove enclosing quotes name = regKey?.GetValue(null).ToString()?.ToLower().Replace("" + (char)34, ""); // Check if value ends with .exe (we remove any command line arguments) if (name != null && !name.EndsWith("exe")) { name = name.Substring(0, name.LastIndexOf(".exe", StringComparison.Ordinal) + 4); } } catch (Exception ex) { name = $"ERROR: An exception of type: {ex.GetType()} occurred in method: {ex.TargetSite} in the following module: {this.GetType()}"; } finally { regKey?.Close(); } return(name); }
/// <summary> /// 压缩 /// </summary> /// <param name="zipname">要解压的文件名</param> /// <param name="zippath">要压缩的文件目录</param> /// <param name="dirpath">初始目录</param> public void EnZip(string zipname, string zippath, string dirpath) { try { the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command"); the_Obj = the_Reg.GetValue(""); the_rar = the_Obj.ToString(); the_Reg.Close(); the_rar = the_rar.Substring(1, the_rar.Length - 7); the_Info = " a " + zipname + " " + zippath; the_StartInfo = new ProcessStartInfo(); the_StartInfo.FileName = the_rar; the_StartInfo.Arguments = the_Info; the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden; the_StartInfo.WorkingDirectory = dirpath; the_Process = new Process(); the_Process.StartInfo = the_StartInfo; the_Process.Start(); } catch (Exception ex) { throw new Exception(ex.Message); } }