Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions PowerKit.Tests/RegistryExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.Runtime.Versioning;
using FluentAssertions;
using Microsoft.Win32;
using PowerKit.Extensions;
using Xunit;

namespace PowerKit.Tests;

public class RegistryExtensionsTests
{
[SkippableFact]
[SupportedOSPlatform("windows")]
public void ContainsSubKey_Exists_Test()
{
Skip.IfNot(OperatingSystem.IsWindows());

// Arrange
Comment thread
Tyrrrz marked this conversation as resolved.
using var key = Registry.CurrentUser.OpenSubKey("Software", true)!;
var subKeyName = $"PowerKit.Tests.{Guid.NewGuid():N}";

try
{
using var subKey = key.CreateSubKey(subKeyName);

// Act & assert
key.ContainsSubKey(subKeyName).Should().BeTrue();
}
finally
{
key.DeleteSubKeyTree(subKeyName, false);
}
}

[SkippableFact]
[SupportedOSPlatform("windows")]
public void ContainsSubKey_NotExists_Test()
{
Skip.IfNot(OperatingSystem.IsWindows());

// Arrange
using var key = Registry.CurrentUser.OpenSubKey("Software", false)!;
Comment thread
Tyrrrz marked this conversation as resolved.

// Act & assert
key.ContainsSubKey("this-sub-key-definitely-does-not-exist").Should().BeFalse();
}
}
22 changes: 22 additions & 0 deletions PowerKit/Extensions/RegistryExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#if NETFRAMEWORK || NET5_0_OR_GREATER
using System.Runtime.Versioning;
using Microsoft.Win32;

namespace PowerKit.Extensions;

internal static class RegistryExtensions
{
extension(RegistryKey key)
{
/// <summary>
/// Checks whether a sub-key with the specified name exists under the registry key.
/// </summary>
[SupportedOSPlatform("windows")]
public bool ContainsSubKey(string name)
Comment thread
Tyrrrz marked this conversation as resolved.
{
using var subKey = key.OpenSubKey(name, false);
Comment thread
Tyrrrz marked this conversation as resolved.
return subKey is not null;
}
}
}
#endif