/// <summary> /// Checks if the specified key can be opened with write permissions /// </summary> /// <param name="registryKey">The key to check</param> /// <returns>True if it can be opened with write permissions, otherwise false</returns> /// <exception cref="ArgumentException">The parent key could not be opened from the Registry key</exception> /// <exception cref="ObjectDisposedException">The <see cref="RegistryKey"/> is closed (closed keys cannot be accessed)</exception> public static bool HasWritePermission(this RegistryKey registryKey) { try { using (var key = registryKey.GetParentKey()) key.OpenSubKey(RegistryHelpers.GetSubKeyName(registryKey.Name))?.Dispose(); return(true); } catch (SecurityException) { return(false); } catch (ObjectDisposedException) { throw; } catch (Exception ex) { throw new ArgumentException("The parent key could not be opened from the Registry key", ex); } }
/// <summary> /// Deletes a registry key and disposes it /// </summary> /// <param name="registryKey">The key to delete</param> /// <param name="recursive">True if all sub-keys and values should be deleted</param> public static void DeleteKey(this RegistryKey registryKey, bool recursive) { // Save the name of the key string name = RegistryHelpers.GetSubKeyName(registryKey.Name); // Get the parent key using (var parent = registryKey.GetParentKey(true)) { // Dispose the key registryKey.Dispose(); if (recursive) { // Delete the key recursively parent.DeleteSubKeyTree(name); } else { // Delete the key parent.DeleteSubKey(name); } } }