using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using Vanara.PInvoke; using static Vanara.PInvoke.Ole32; using static Vanara.PInvoke.PropSys; namespace Vanara.Windows.Shell { /// An in-memory property store. /// public class MemoryPropertyStore : PropertyStore { /// Initializes a new instance of the class. public MemoryPropertyStore() { PSCreateMemoryPropertyStore(typeof(IPropertyStore).GUID, out var ppv).ThrowIfFailed(); iPropertyStore = (IPropertyStore)ppv; } /// Initializes a new instance of the class from a stream. /// The stream. /// stream public MemoryPropertyStore(IStream stream) : this() { if (stream is null) throw new ArgumentNullException(nameof(stream)); stream.Stat(out var stat, 0); if (stat.cbSize > 128 * 1024) throw Marshal.GetExceptionForHR(HRESULT.STG_E_MEDIUMFULL); else if (stat.cbSize > 0) ((IPersistStream)iPropertyStore).Load(stream); } /// Clones a property store to a memory property store. /// The property store to clone. /// The cloned memory property store. /// ps public static MemoryPropertyStore ClonePropertyStoreToMemory(IPropertyStore ps) { if (ps is null) throw new ArgumentNullException(nameof(ps)); var ms = new MemoryPropertyStore(); var cnt = ps.GetCount(); for (var i = 0U; i < cnt; i++) { var key = ps.GetAt(i); ms.Add(key, ps.GetValue(key)); } return ms; } /// Saves the contents of this property store to a stream. /// The stream that recieves the contents of this property store. /// stream public void SaveToStream(IStream stream) { if (stream is null) throw new ArgumentNullException(nameof(stream)); var psps = (IPersistSerializedPropStorage)iPropertyStore; var pPersistStream = (IPersistStream)psps; pPersistStream.Save(stream, true); } } }