using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Vanara.Windows.Shell.Registration
{
/// A collection of values under a key that is treated as a collection of strings.
///
internal class RegBasedKeyCollection : ICollection, IDisposable
{
/// The base key from which to perform all queries.
protected internal RegistryKey key;
/// Initializes a new instance of the class.
/// The key to use as the base key for queries.
/// if set to true the supplied was opened read-only.
protected internal RegBasedKeyCollection(RegistryKey key, bool readOnly)
{
if (key is null && !readOnly) throw new ArgumentNullException(nameof(key));
this.key = key;
IsReadOnly = readOnly;
}
/// Gets the count.
/// The count.
public int Count => key?.ValueCount ?? 0;
/// Gets or sets a value indicating whether these settings are read-only.
public bool IsReadOnly { get; }
/// Adds the specified item.
/// The item.
public void Add(string item) { EnsureWritable(); key.SetValue(item, string.Empty, RegistryValueKind.String); }
/// Clears this instance.
public void Clear() { EnsureWritable(); key.DeleteAllSubItems(); }
/// Determines whether this instance contains the object.
/// The item.
/// if [contains] [the specified item]; otherwise, .
public bool Contains(string item) => key?.HasValue(item) ?? false;
/// Copies to.
/// The array.
/// Index of the array.
public void CopyTo(string[] array, int arrayIndex) { if (key != null) Array.Copy(key.GetValueNames(), 0, array, arrayIndex, Count); }
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
public void Dispose() => key?.Close();
/// Gets the enumerator.
///
public IEnumerator GetEnumerator() => (key?.GetValueNames().Cast() ?? new string[0]).GetEnumerator();
/// Removes the specified item.
/// The item.
///
public bool Remove(string item) { EnsureWritable(); try { key.DeleteValue(item, true); return true; } catch { return false; } }
/// Gets the enumerator.
///
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// Checks the ReadOnly flag and throws an exception if it is true.
protected void EnsureWritable() { if (IsReadOnly) throw new NotSupportedException("The collection is read only."); }
}
}