| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="WindowsRegistryQuery.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System.Runtime.Versioning; |
| | | 8 | | using Microsoft.Win32; |
| | | 9 | | using MyNet.IO.Registry; |
| | | 10 | | |
| | | 11 | | namespace MyNet.Platform.Windows.Registry; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Implements a registry query using the Windows Registry API. |
| | | 15 | | /// </summary> |
| | | 16 | | [SupportedOSPlatform("windows")] |
| | | 17 | | public sealed class WindowsRegistryQuery(IRegistryValueConverter converter) : IRegistryQuery |
| | | 18 | | { |
| | 24 | 19 | | private readonly RegistryKey _root = Microsoft.Win32.Registry.CurrentUser; |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// Finds a registry key by searching for a specific value under a parent key. |
| | | 23 | | /// </summary> |
| | | 24 | | /// <param name="parent">The parent registry path.</param> |
| | | 25 | | /// <param name="valueKey">The name of the value to search for.</param> |
| | | 26 | | /// <param name="value">The value to match.</param> |
| | | 27 | | /// <typeparam name="T">The type of the value.</typeparam> |
| | | 28 | | /// <returns>The registry path of the matching key, or null if not found.</returns> |
| | | 29 | | public RegistryPath? FindByValue<T>(RegistryPath parent, string valueKey, T value) |
| | | 30 | | { |
| | 6 | 31 | | using var key = _root.OpenSubKey(parent.ToString()); |
| | 6 | 32 | | if (key is null) |
| | 3 | 33 | | return null; |
| | | 34 | | |
| | 15 | 35 | | foreach (var childName in key.GetSubKeyNames()) |
| | | 36 | | { |
| | 6 | 37 | | using var child = key.OpenSubKey(childName); |
| | | 38 | | |
| | 6 | 39 | | var raw = child?.GetValue(valueKey); |
| | 6 | 40 | | if (raw is null) |
| | 0 | 41 | | continue; |
| | | 42 | | |
| | 6 | 43 | | var converted = converter.ConvertFrom(raw, typeof(T)); |
| | | 44 | | |
| | 6 | 45 | | if (Equals(converted, value)) |
| | 3 | 46 | | return RegistryPath.Combine(parent.ToString(), childName); |
| | | 47 | | } |
| | | 48 | | |
| | 0 | 49 | | return null; |
| | 6 | 50 | | } |
| | | 51 | | } |
| | | 52 | | |