public Boolean RemoveSubKey(String name, Boolean isRecursive = false, Boolean isThrow = false) { try { CheckSafe(true); if (isRecursive) { _registryKey?.DeleteSubKeyTree(name); } else { _registryKey?.DeleteSubKey(name); } return(true); } catch (Exception) { if (isThrow) { throw; } } return(false); }
public static void DeleteAllRegData() //Подготовка к ПОЛНОМУ УДАЛЕНИЮ программы { RegistryKey rk = null; RegistryKey rks = null; try { rks = Registry.CurrentUser.CreateSubKey("Software"); rk = Registry.CurrentUser.CreateSubKey(BeginKeyName); if (rk == null) { return; } var temp = new List <string>(); temp.AddRange(rk.GetSubKeyNames()); if (temp.Count < 2) { rks?.DeleteSubKeyTree("Sepo"); } else if (temp.Count > 1) { rk.DeleteSubKeyTree("FW Launcher Beta"); } } finally { rk?.Close(); rks?.Close(); } }
public static void UnregisterMenuItem(string app) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw new NotSupportedException("The platform is not supported."); } using RegistryKey shellFiles = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\Classes\\*\\shell", writable: true); shellFiles?.DeleteSubKeyTree(app, throwOnMissingSubKey: false); using RegistryKey shellDirectory = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\Classes\\Directory\\shell", writable: true); shellDirectory?.DeleteSubKeyTree(app, throwOnMissingSubKey: false); }
/// <summary> /// Removes the program from the Windows Explorer context menu. /// </summary> /// <param name="allUsers">Whether to uninstall for all users</param> /// <param name="types">Image file types to uninstall the handler for</param> public static void UninstallHandler(bool allUsers, ImageFileType[] types) { foreach (ImageFileType fileType in types) { foreach (string typeExt in FileTypeMap[fileType]) { using (RegistryKey shellKey = GetShellKey(allUsers, typeExt)) { shellKey?.DeleteSubKeyTree(VerbName, false); } } } }
/// <summary> /// Removes all file associations for the given extension. /// <para>WARNING: Method requires admin privileges.</para> /// </summary> /// <exception cref="ArgumentException" /> public static void ClearAssociations(string extension) { if (!extension.StartsWith(".")) { throw new ArgumentException(BadExtensionMessage); } Registry.ClassesRoot.DeleteSubKey(extension, false); using (RegistryKey fileExtsKey = Registry.CurrentUser.OpenSubKey(FileExtsRegistryPath, true)) fileExtsKey?.DeleteSubKeyTree(extension, false); // Tell the explorer that the file association has been changed NativeMethods.SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero); }
public static void DeleteAllAccRegData() //Удалить ВСЕ АККАУНТЫ и их данные из РЕЕСТРА { RegistryKey rk = null; try { rk = Registry.CurrentUser.CreateSubKey(RegKeyName); rk?.DeleteSubKeyTree("AccData"); } finally { rk?.Close(); } }
public bool CleanupRegistry() { try { using (RegistryKey appKey = Registry.LocalMachine.OpenSubKey(AppsKey, true)) appKey?.DeleteSubKeyTree(AppBinary, false); using (RegistryKey uninstKey = Registry.LocalMachine.OpenSubKey(UninstallKey, true)) uninstKey?.DeleteSubKeyTree(AppKey, false); } catch (Exception err) { Console.WriteLine(err.Message); return(false); } return(true); }
/// <summary> /// Permite quitar un comando asociado con una extensión /// </summary> public void DeleteLinkCommandExtension(string extension, string command) { if (!string.IsNullOrEmpty(command) && !command.Equals("open", StringComparison.CurrentCultureIgnoreCase)) { string programID; // Normaliza la extensión extension = NormalizeExtension(extension); // Obtiene el ID de programa de la extensión programID = GetProgIdFromExtension(extension); // Elimina la clave del registro if (!string.IsNullOrEmpty(programID) && programID.Length > 0) { using (RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(programID, true)) { registryKey?.DeleteSubKeyTree($"shell\\{command}"); } } } }
public void ItCanFindVisualStudioDependents() { DependencyProvider dep = new DependencyProvider(".NET_SDK_TEST_PROVIDER_KEY", allUsers: false); try { // We should not have any dependents Assert.Empty(dep.Dependents); // Write the VS dependents key dep.AddDependent(DependencyProvider.VisualStudioDependentKeyName); Assert.True(dep.HasVisualStudioDependency); } finally { // Clean up and delete everything using RegistryKey providerKey = dep.BaseKey.OpenSubKey(DependencyProvider.DependenciesKeyRelativePath, writable: true); providerKey?.DeleteSubKeyTree(dep.ProviderKeyName); } }
/// <summary> /// Remove the specified dependent from the provider key. Optionally, if this is the final dependent, /// the provider key can also be removed. This is typically done during an uninstall. /// </summary> /// <param name="dependent">The dependent to remove.</param> /// <param name="removeProvider">When <see langword="true"/>, delete the provider key if the dependent being /// removed is the last dependent.</param> public void RemoveDependent(string dependent, bool removeProvider) { if (dependent is null) { throw new ArgumentNullException(nameof(dependent)); } if (string.IsNullOrWhiteSpace(dependent)) { throw new ArgumentException($"{nameof(dependent)} cannot be empty."); } using RegistryKey dependentsKey = BaseKey.OpenSubKey(DependentsKeyPath, writable: true); dependentsKey?.DeleteSubKeyTree(dependent); if ((removeProvider) && (Dependents.Count() == 0)) { using RegistryKey providerKey = BaseKey.OpenSubKey(DependenciesKeyRelativePath, writable: true); providerKey?.DeleteSubKeyTree(ProviderKeyName); } }
public void ItCanAddDependents() { // We cannot create per-machine entries unless the tests run elevated. The results are the // the same, it's only the base key that's different DependencyProvider dep = new DependencyProvider(".NET_SDK_TEST_PROVIDER_KEY", allUsers: false); try { // We should not have any dependents Assert.Empty(dep.Dependents); dep.AddDependent("Microsoft.NET.SDK,v6.0.100"); Assert.Single(dep.Dependents); Assert.Equal("Microsoft.NET.SDK,v6.0.100", dep.Dependents.First()); } finally { // Clean up and delete everything using RegistryKey providerKey = dep.BaseKey.OpenSubKey(DependencyProvider.DependenciesKeyRelativePath, writable: true); providerKey?.DeleteSubKeyTree(dep.ProviderKeyName); } }
public void ItWillNotRemoveTheProviderIfOtherDependentsExist() { DependencyProvider dep = new DependencyProvider(".NET_SDK_TEST_PROVIDER_KEY", allUsers: false); try { // Write multiple dependents dep.AddDependent(DependencyProvider.VisualStudioDependentKeyName); dep.AddDependent("Microsoft.NET.SDK,v6.0.100"); Assert.Equal(2, dep.Dependents.Count()); dep.RemoveDependent("Microsoft.NET.SDK,v6.0.100", removeProvider: true); Assert.True(dep.HasVisualStudioDependency); } finally { // Clean up and delete everything using RegistryKey providerKey = dep.BaseKey.OpenSubKey(DependencyProvider.DependenciesKeyRelativePath, writable: true); providerKey?.DeleteSubKeyTree(dep.ProviderKeyName); } }
public void RemoveGroup(string groupName) { storageKey.DeleteSubKeyTree(groupName); }
public static bool RenameSubKey(RegistryKey parentKey, string subKeyName, string newSubKeyName) { CopyKey(parentKey, subKeyName, newSubKeyName); parentKey.DeleteSubKeyTree(subKeyName); return(true); }
public static void Delete(Cue cue) { var elementKey = $@"Cues\{cue.Id}"; try { root.DeleteSubKeyTree(elementKey); } catch { } }
/// <summary> /// Deletes Registry keys/values (if they exist) to unassociate .iro mod files with 7H /// </summary> /// <param name="key"> could be HKEY_CLASSES_ROOT or HKEY_CURRENT_USER/Software/Classes </param> private static bool RemoveIroFileAssociationFromRegistry(RegistryKey key) { try { List <string> subkeys = key.GetSubKeyNames().Where(k => k == "7thHeaven" || k == ".iro" || k == ".irop").ToList(); bool deletedKeys = false; if (subkeys.Contains("7thHeaven")) { var progKey = key.OpenSubKey("7thHeaven", true); string[] subKeys = progKey.GetSubKeyNames(); if (subKeys.Any(k => k == "shell")) { var shell = progKey.OpenSubKey("shell", true); if (shell.GetSubKeyNames().Any(k => k == "open")) { shell.DeleteSubKeyTree("open"); deletedKeys = true; } } if (subKeys.Any(k => k == ".iro")) { progKey.DeleteSubKeyTree(".iro"); deletedKeys = true; } if (subKeys.Any(k => k == "DefaultIcon")) { progKey.DeleteSubKeyTree("DefaultIcon"); deletedKeys = true; } } if (subkeys.Contains(".iro")) { key.DeleteSubKeyTree(".iro"); deletedKeys = true; } if (subkeys.Contains(".irop")) { key.DeleteSubKeyTree(".irop"); deletedKeys = true; } if (deletedKeys) { //Refresh Shell/Explorer so icon cache updates //do this now because we don't care so much about assoc. URL if it fails SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero); } return(true); } catch (Exception e) { Logger.Warn(e); // could be error thrown if already deleted return(false); } }
private void btn_cleanup_Click(object sender, EventArgs e) { MessageBox.Show("Attention: Make sure you've uninstalled the TeamViewer otherwise you will get clean up error"); var confirmResult = MessageBox.Show("Are you sure you've uninstalled the TeamViewer?", "Confirm Cleanup!", MessageBoxButtons.YesNo); if (confirmResult == DialogResult.Yes) { btn_cleanup.Text = "Cleaning Please wait..."; btn_cleanup.Enabled = false; try { if (Directory.Exists(@"C:\Program Files\TeamViewer")) { System.IO.Directory.Delete(@"C:\Program Files\TeamViewer", true); } if (Directory.Exists(@"C:\Program Files(x86)\TeamViewer")) { System.IO.Directory.Delete(@"C:\Program Files(x86)\TeamViewer", true); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); er = 1; } try { RegistryKey regKey = Registry.LocalMachine.OpenSubKey("Software", true); //regKey.DeleteSubKey("TeamViewer", true); regKey.DeleteSubKeyTree("TeamViewer", true); regKey.Close(); } catch (Exception ex) { //MessageBox.Show(ex.ToString()); } var localApplicationData = Environment.ExpandEnvironmentVariables("%appdata%"); string localpath = localApplicationData + @"\TeamViewer"; try { if (Directory.Exists(@localpath)) { System.IO.Directory.Delete(@localpath, true); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); er = 1; } btn_cleanup.Text = "Start Clean up Now"; btn_cleanup.Enabled = true; if (er == 0) { MessageBox.Show("Cleanup has been completed without any errors"); } else { MessageBox.Show("Cleanup has been completed with some errors"); } } }
// レジストリキーをコピー private void CopyRegistryKey(string source, string destination) { Action <RegistryKey, RegistryKey> copyRegKey = null; copyRegKey = (srcKey, dstKey) => { foreach (string paramName in srcKey.GetValueNames()) { RegistryValueKind valueKind = srcKey.GetValueKind(paramName); dstKey.SetValue( paramName, valueKind == RegistryValueKind.ExpandString ? srcKey.GetValue(paramName, "", RegistryValueOptions.DoNotExpandEnvironmentNames) : srcKey.GetValue(paramName), valueKind); } foreach (string keyName in srcKey.GetSubKeyNames()) { using (RegistryKey subSrcKey = srcKey.OpenSubKey(keyName, false)) using (RegistryKey subDstKey = dstKey.CreateSubKey(keyName, true)) { try { copyRegKey(subSrcKey, subDstKey); } catch (System.Security.SecurityException) { Console.WriteLine("アクセス拒否:SecurityException\r\n" + keyName); } catch (UnauthorizedAccessException) { Console.WriteLine("アクセス拒否:UnauthorizedAccessException\r\n" + keyName); } catch (ArgumentException) { // 無効なValueKindのレジストリ値への対策 // reg copyコマンドでコピー実行 using (Process proc = new Process()) { proc.StartInfo.FileName = "reg.exe"; proc.StartInfo.Arguments = $@"copy ""{subSrcKey.ToString()}"" ""{subDstKey.ToString()}"" /s /f"; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.Start(); proc.WaitForExit(); } } } } }; using (RegistryKey sourceKey = RegistryControl.GetRegistryKey(source, false, true)) using (RegistryKey destinationKey = RegistryControl.GetRegistryKey(destination, true, true)) { // テスト自動生成 _generator.RegistryPath(source); _generator.RegistryPath(destination); _generator.RegistryCompare(source, destination, true, false); copyRegKey(sourceKey, destinationKey); // コピー元を削除する場合 sourceKey.DeleteSubKeyTree(""); } }
public override void DeleteObject(Guid obj) { string path = string.Format(CultureInfo.InvariantCulture, ObjectTypePathTemplate, obj.ToString("B")); _rootKey.DeleteSubKeyTree(path); }
static void RemoveLicenseInRegistry() { string[] dict = LoadDictionary(); Console.Write("Scanning: "); int curLeft = Console.CursorLeft; int curTop = Console.CursorTop; RegistryCandidateList candidates = new RegistryCandidateList(); RegistryKey clsid = Registry.ClassesRoot.OpenSubKey("Wow6432Node", true).OpenSubKey("CLSID", true); int printCounter = 0; foreach (string id in clsid.GetSubKeyNames()) { if ((++printCounter % 16) == 0) { Console.CursorLeft = curLeft; Console.CursorTop = curTop; Console.Write(id); } RegistryKey key = clsid.OpenSubKey(id); if (key.SubKeyCount < 8) { continue; } int scrambledCount = 0; int symbolCount = 0; foreach (string member in key.GetSubKeyNames()) { try { var fld = key.OpenSubKey(member); if (fld.ValueCount == 1 && fld.SubKeyCount == 0 && fld.GetValueKind(null) == RegistryValueKind.String) { string data = (string)fld.GetValue(null); symbolCount += CountSymbol(data); if (!HasAnyWord(dict, member)) { scrambledCount++; } } } catch { } } if (scrambledCount > 0) { int score = scrambledCount + symbolCount; candidates.Position(score, key); } } Console.WriteLine(); foreach (RegistryKey key in candidates.GetCandidates()) { Console.WriteLine(key.Name); foreach (string member in key.GetSubKeyNames()) { Console.Write(" "); Console.WriteLine(member); } Console.Write("Remove this? Confirm with (Y/n): "); if (Console.ReadKey().Key == ConsoleKey.Y) { if (!dryRun) { clsid.DeleteSubKeyTree(key.Name); } } Console.WriteLine(); } try { Console.WriteLine("Removing Licenses registry key."); if (!dryRun) { Registry.CurrentUser.OpenSubKey("Software", true).DeleteSubKey("Licenses"); } } catch { Console.WriteLine("Can't remove registry key."); } }
/// <summary> /// Upgrades from versions up to and including v11 (beta 1) /// </summary> private static void UpgradeFrom_Earlier(RegistryKey reg) { foreach (string themeName in reg.GetSubKeyNames()) { using (RegistryKey themeKey = reg.OpenSubKey(themeName)) { if (themeKey == null) { continue; } string name = themeKey.GetValue("Name") as string; if (string.IsNullOrEmpty(name)) { continue; } using (RegistryKey newKey = reg.CreateSubKey(name)) { newKey.SetValue("VisibleAligned", 1); newKey.SetValue("VisibleUnaligned", 0); newKey.SetValue("ExtendInwardsOnly", 1); // Upgrade the old EmptyLineMode enumeration string elm = themeKey.GetValue("EmptyLineMode") as string ?? "SameAsAboveLogical"; switch (elm) { case "NoGuides": newKey.SetValue("VisibleEmpty", 0); newKey.SetValue("VisibleEmptyAtEnd", 0); break; case "SameAsLineAboveActual": newKey.SetValue("VisibleEmpty", 1); newKey.SetValue("VisibleEmptyAtEnd", 0); break; case "SameAsLineAboveLogical": newKey.SetValue("VisibleEmpty", 1); newKey.SetValue("VisibleEmptyAtEnd", 1); break; case "SameAsLineBelowActual": newKey.SetValue("VisibleEmpty", 1); newKey.SetValue("VisibleEmptyAtEnd", 0); break; case "SameAsLineBelowLogical": newKey.SetValue("VisibleEmpty", 1); newKey.SetValue("VisibleEmptyAtEnd", 1); break; } // Upgrade the old VisibleAtText setting (default to false) bool ate = string.Equals("True", themeKey.GetValue("VisibleAtText") as string, StringComparison.InvariantCultureIgnoreCase); newKey.SetValue("VisibleAtTextEnd", ate ? 1 : 0); // Copy the default color/style to Default, Unaligned and Caret themes. // Change the Caret theme color to Red, or Teal if it was already red. using (RegistryKey subKey1 = newKey.CreateSubKey("Default")) using (RegistryKey subKey2 = newKey.CreateSubKey("Unaligned")) { bool visible = !string.Equals("False", themeKey.GetValue("Visible") as string, StringComparison.InvariantCultureIgnoreCase); string color = themeKey.GetValue("LineColor") as string ?? "Teal"; string style = themeKey.GetValue("LineStyle") as string ?? "Dotted"; subKey1.SetValue("Visible", visible ? 1 : 0); subKey2.SetValue("Visible", visible ? 1 : 0); subKey1.SetValue("LineColor", color); subKey2.SetValue("LineColor", color); subKey1.SetValue("LineStyle", style); subKey2.SetValue("LineStyle", style); subKey1.SetValue("HighlightColor", color == "Red" ? "Teal" : "Red"); subKey1.SetValue("HighlightStyle", style); subKey2.SetValue("HighlightColor", color == "Red" ? "Teal" : "Red"); subKey2.SetValue("HighlightStyle", style); } // Copy the existing indent overrides. foreach (string subkeyName in themeKey.GetSubKeyNames()) { int formatIndex; if (!int.TryParse(subkeyName, out formatIndex)) { continue; } using (RegistryKey subKey1 = themeKey.OpenSubKey(subkeyName)) using (RegistryKey subKey2 = newKey.CreateSubKey(subkeyName)) { bool visible = !string.Equals("False", subKey1.GetValue("Visible") as string, StringComparison.InvariantCultureIgnoreCase); string color = subKey1.GetValue("LineColor") as string ?? "Teal"; string style = subKey1.GetValue("LineStyle") as string ?? "Dotted"; subKey2.SetValue("Visible", visible ? 1 : 0); subKey2.SetValue("LineColor", color); subKey2.SetValue("LineStyle", style); subKey2.SetValue("HighlightColor", color == "Red" ? "Teal" : "Red"); subKey2.SetValue("HighlightStyle", style); } } } } reg.DeleteSubKeyTree(themeName, false); } }
internal static bool CreateUninstaller() { Guid guid = GetUninstallId(); if (guid == Guid.Empty) { return(false); } try { string guidText = guid.ToString(@"B"); using (RegistryKey parent = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", false)) { using (RegistryKey check = parent.OpenSubKey(guidText)) { if (check != null && (string)check.GetValue(@"DisplayIcon") == OsuMain.FullPath) { return(true); } } } try { using (RegistryKey parent = Registry.ClassesRoot.OpenSubKey(@"Installer\Products", true)) { using (RegistryKey check = parent.OpenSubKey(@"6242953CE135011419D1FBCE2EEC82C4")) if (check != null) { //old installer parent.DeleteSubKeyTree(@"6242953CE135011419D1FBCE2EEC82C4"); } } } catch { } using (RegistryKey parent = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", true)) { if (parent == null) { return(false); } try { using (RegistryKey check = parent.OpenSubKey(@"{C3592426-531E-4110-911D-BFECE2CE284C}")) if (check != null) { //old uninstaller parent.DeleteSubKeyTree(@"{C3592426-531E-4110-911D-BFECE2CE284C}"); } } catch { } using (RegistryKey key = parent.OpenSubKey(guidText, true) ?? parent.CreateSubKey(guidText)) { if (key == null) { return(false); } key.SetValue(@"DisplayName", @"osu!"); key.SetValue(@"ApplicationVersion", @"latest"); key.SetValue(@"Publisher", @"ppy Pty Ltd"); key.SetValue(@"DisplayIcon", OsuMain.FullPath); key.SetValue(@"DisplayVersion", @"latest"); key.SetValue(@"EstimatedSize", 125952, RegistryValueKind.DWord); key.SetValue(@"NoModify", 1, RegistryValueKind.DWord); key.SetValue(@"NoRepair", 1, RegistryValueKind.DWord); key.SetValue(@"URLInfoAbout", "https://osu.ppy.sh"); key.SetValue(@"Contact", @"*****@*****.**"); key.SetValue(@"InstallDate", DateTime.Now.ToString(@"yyyyMMdd")); key.SetValue(@"UninstallString", OsuMain.FullPath + @" -uninstall"); } } } catch (Exception ex) { return(false); } return(true); }
public void DeleteTree(RegistryKey registryKey, string subkey) { registryKey.DeleteSubKeyTree(subkey, false); registryKey.Close(); }
public void DeleteLocation(string location) { baseKey.DeleteSubKeyTree(location); }
public void SetUp() { hkcu.DeleteSubKeyTree(TestKeyPath, false); }
/// <summary> /// Move subkey under a new parent. /// </summary> public static void MoveSubKey(this RegistryKey parentKey, string subKeyName, RegistryKey newParentKey, string newSubKeyName) { CopySubKey(parentKey, subKeyName, newParentKey, newSubKeyName); parentKey.DeleteSubKeyTree(subKeyName); }
public void Remove(IEntry <TeaTimerDefinition> value) { _reg.DeleteSubKeyTree(_entries[value].Key.ToString("B")); _entries.Remove(value); NormalizePositions(); }
public static void SaveConfiguration(Configuration config, bool recentUsageOnly) { RegistryKey key = Registry.CurrentUser.CreateSubKey(APPLICATION_REGISTRY_KEY); if (key != null) { if (!recentUsageOnly) { key.SetValue("Window Visible", config.WindowVisible.ToString(), RegistryValueKind.String); key.SetValue("Start With Windows", config.StartWithWindows.ToString(), RegistryValueKind.String); RegistryKey applicationsKey = key.CreateSubKey("Applications"); if (applicationsKey != null) { string[] subKeyNames = applicationsKey.GetSubKeyNames(); foreach (string subKeyName in subKeyNames) { if (subKeyName.StartsWith("Application ")) { applicationsKey.DeleteSubKeyTree(subKeyName); } } for (int i = 0; i < config.Applications.Count; i++) { RegistryKey applicationKey = applicationsKey.CreateSubKey("Application " + i.ToString("00")); if (applicationKey != null) { applicationKey.SetValue("ID", config.Applications[i].ID.ToString(), RegistryValueKind.String); applicationKey.SetValue("Name", config.Applications[i].Name, RegistryValueKind.String); applicationKey.SetValue("Path", config.Applications[i].Path, RegistryValueKind.String); applicationKey.SetValue("Arguments", config.Applications[i].Arguments ?? string.Empty, RegistryValueKind.String); applicationKey.SetValue("Group", config.Applications[i].Group ?? string.Empty, RegistryValueKind.String); for (int j = 0; j < config.Applications[i].Sets.Count; j++) { applicationKey.SetValue("Set " + j.ToString("00"), config.Applications[i].Sets[j]); } applicationKey.Close(); } } applicationsKey.Close(); } } RegistryKey recentKey = key.CreateSubKey("Recent"); if (recentKey != null) { string[] subKeyNames = recentKey.GetSubKeyNames(); foreach (string subKeyName in subKeyNames) { if (subKeyName.StartsWith("Recent ")) { recentKey.DeleteSubKeyTree(subKeyName); } } for (int i = 0; i < config.RecentUsages.Count; i++) { RegistryKey recentUsageKey = recentKey.CreateSubKey("Recent " + i.ToString("00")); if (recentUsageKey != null) { recentUsageKey.SetValue("ID", config.RecentUsages[i].ID, RegistryValueKind.String); recentUsageKey.SetValue("Count", config.RecentUsages[i].Count, RegistryValueKind.DWord); recentUsageKey.Close(); } } recentKey.Close(); } key.Close(); } }
public override string Run(bool quiet) { if (!quiet) { try { Application.EnableVisualStyles(); } catch { } } string root = Environment.GetEnvironmentVariable("OLYMPUS_ROOT"); if (string.IsNullOrEmpty(root)) { root = Win32RegHelper.OpenOrCreateKey(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\Olympus", false)?.GetValue("InstallLocation") as string; } if (string.IsNullOrEmpty(root)) { root = Path.GetDirectoryName(Path.GetDirectoryName(Program.SelfPath)); } if (!File.Exists(Path.Combine(root, "main.exe")) || !File.Exists(Path.Combine(root, "love.dll")) || !Directory.Exists(Path.Combine(root, "sharp"))) { if (!quiet) { MessageBox.Show("The Olympus uninstaller has encountered an error:\nCan't verify the main folder.\n\nPlease delete %AppData%/Olympus manually.", "Olympus", MessageBoxButtons.OK); } return(null); } if (Program.SelfPath.StartsWith(root)) { string tmpDir = Path.Combine(Path.GetTempPath(), "Olympus.Uninstall"); string tmp = Path.Combine(tmpDir, "Olympus.Sharp.exe"); try { if (!Directory.Exists(tmpDir)) { Directory.CreateDirectory(tmpDir); } string tmpDep = Path.Combine(tmpDir, "MonoMod.Utils.dll"); if (File.Exists(tmpDep)) { File.Delete(tmpDep); } File.Copy(Path.Combine(Path.GetDirectoryName(Program.SelfPath), "MonoMod.Utils.dll"), tmpDep); if (File.Exists(tmp)) { File.Delete(tmp); } File.Copy(Program.SelfPath, tmp); } catch { if (!quiet) { MessageBox.Show("The Olympus uninstaller has encountered an error:\nCan't copy the uninstaller into %TMP%.\n\nPlease delete %AppData%/Olympus manually.", "Olympus", MessageBoxButtons.OK); } return(null); } Environment.SetEnvironmentVariable("OLYMPUS_ROOT", root); Process process = new Process(); process.StartInfo.FileName = tmp; process.StartInfo.Arguments = "--uninstall" + (quiet ? " --quiet" : ""); Environment.CurrentDirectory = process.StartInfo.WorkingDirectory = tmpDir; process.Start(); return(null); } if (!quiet && MessageBox.Show($"Do you want to uninstall Olympus from the following folder?\n{root}\n\nEverest and all your mods will stay installed.", "Olympus", MessageBoxButtons.YesNo) != DialogResult.Yes) { return(null); } try { Directory.Delete(root, true); } catch { if (!quiet) { MessageBox.Show("The Olympus uninstaller has encountered an error:\nCan't delete the Olympus folder.\n\nPlease delete %AppData%/Olympus manually.", "Olympus", MessageBoxButtons.OK); } return(null); } try { using (RegistryKey key = Win32RegHelper.OpenOrCreateKey(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall", true)) key?.DeleteSubKeyTree("Olympus"); } catch { } if (!quiet) { MessageBox.Show("Olympus was uninstalled successfully.", "Olympus", MessageBoxButtons.OK); } return(null); }
public static void Set(string[] fileExtensions) { char[] trimChars = new char[] { ' ', '*', '.' }; List <RegistryKey> regKeyCreatedList = new List <RegistryKey>(); // See the link below for more info // http://www.howtogeek.com/107965/how-to-add-any-application-shortcut-to-windows-explorers-context-menu foreach (string fileExtension in fileExtensions) { string extension = "." + fileExtension.Trim(trimChars).ToLower(); try { // HKEY_CLASSES_ROOT\<file extension including the dot> // Below we will use the example ".srt" (an extension commonly used for subtitle text files) // HKEY_CLASSES_ROOT\.srt RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(extension, true); if (regKey == null) { // Create new entry for the extension under HKEY_CLASSES_ROOT regKey = Registry.ClassesRoot.CreateSubKey(extension); regKey.SetValue("", extension.TrimStart('.') + "file", RegistryValueKind.String); // Default value regKey.SetValue("Content Type", "text/plain", RegistryValueKind.String); regKey.SetValue("PerceivedType", "text", RegistryValueKind.String); regKey.Close(); regKeyCreatedList.Add(regKey); regKey = Registry.ClassesRoot.OpenSubKey(extension, true); } object regCRAppValue = regKey.GetValue(""); // Default value if (regCRAppValue.GetType() != typeof(string)) { throw new Exception(string.Format( "Cannot read default value of HKEY_CLASSES_ROOT\\{0} as it's not a string.\nCurrent value: {1}", extension, regCRAppValue)); } string regCRAppName = (string)regCRAppValue; // HKEY_CLASSES_ROOT\srtfile RegistryKey regKeyCRApp = Registry.ClassesRoot.OpenSubKey(regCRAppName, true); if (regKeyCRApp == null) { regKeyCRApp = Registry.ClassesRoot.CreateSubKey(regCRAppName); regKeyCRApp.Close(); regKeyCreatedList.Add(regKeyCRApp); regKeyCRApp = Registry.ClassesRoot.OpenSubKey(regCRAppName, true); } // HKEY_CLASSES_ROOT\srtfile\shell RegistryKey regKeyCRAppShell = regKeyCRApp.OpenSubKey("shell", true); if (regKeyCRAppShell == null) { regKeyCRAppShell = regKeyCRApp.CreateSubKey("shell"); regKeyCRAppShell.Close(); regKeyCreatedList.Add(regKeyCRAppShell); regKeyCRAppShell = regKeyCRApp.OpenSubKey("shell", true); } // HKEY_CLASSES_ROOT\srtfile\shell\<text in right click> // ex: HKEY_CLASSES_ROOT\srtfile\shell\Search and Replace RegistryKey regKeyCRAppShellCommandName = regKeyCRAppShell.OpenSubKey(CommandName, true); if (regKeyCRAppShellCommandName == null) { // The right click text that will appear regKeyCRAppShellCommandName = regKeyCRAppShell.CreateSubKey(CommandName); regKeyCRAppShellCommandName.Close(); regKeyCreatedList.Add(regKeyCRAppShellCommandName); regKeyCRAppShellCommandName = regKeyCRAppShell.OpenSubKey(CommandName, true); } // HKEY_CLASSES_ROOT\srtfile\shell\Search and Replace\command RegistryKey regKeyCRAppShellCommandNameCommand = regKeyCRAppShellCommandName.OpenSubKey("command", true); if (regKeyCRAppShellCommandNameCommand == null) { // Command used to invoke this app (in the Default value) regKeyCRAppShellCommandNameCommand = regKeyCRAppShellCommandName.CreateSubKey("command"); regKeyCRAppShellCommandNameCommand.Close(); regKeyCreatedList.Add(regKeyCRAppShellCommandNameCommand); regKeyCRAppShellCommandNameCommand = regKeyCRAppShellCommandName.OpenSubKey("command", true); } // HKEY_CLASSES_ROOT\srtfile\shell\Search and Replace\command\<command line instructions> object regCommandValue = regKeyCRAppShellCommandNameCommand.GetValue(""); if (regCommandValue == null || (regCommandValue.GetType() == typeof(string) && string.IsNullOrEmpty((string)regCommandValue))) { regKeyCRAppShellCommandNameCommand.SetValue( "", string.Format("{0}", Application.ExecutablePath), RegistryValueKind.ExpandString); } // else, entry already exists, do nothing } catch (UnauthorizedAccessException ex) { string error = ex.Message; // Rollback entries that were added to the registry (LIFO) try { for (int i = regKeyCreatedList.Count - 1; i >= 0; i--) { RegistryKey regKey = regKeyCreatedList[i]; regKey.DeleteSubKeyTree(""); // TODO: verify this works } } catch (Exception ex2) { error += "\n\nIn addition, there was the following error trying to rollback:\n" + ex2.Message; } MessageBox.Show(error, "Not enough permissions to update the registry"); } } }