feat(windows): add removable volume watcher, ejector and format dialog
VolumeInfo reads label, file system, serial, capacity, drive type and DCIM
presence (no "insert disk" prompts) and exposes the card identity
{serial:X8}-{label}-{capacity}. RemovableVolumeWatcher runs a hidden
top-level window on its own message loop for WM_DEVICECHANGE volume unit
masks (message-only windows receive no broadcasts) plus a 3 s DriveInfo poll,
diffing snapshots so each change is raised once. VolumeEjector locks
(with retries), dismounts, allows removal and ejects; FormatDialog shows
SHFormatDrive with quick format preselected and refuses the system drive.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
6 files changed
+723
No files matched your search
@@ -0,0 +1,57 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Core.Windows.Devices;
|
||||
|
||||
/// <summary>Outcome of the Windows format dialog.</summary>
|
||||
public enum FormatDialogResult
|
||||
{
|
||||
/// <summary>The user formatted the volume.</summary>
|
||||
Formatted,
|
||||
|
||||
/// <summary>The user closed the dialog without formatting.</summary>
|
||||
Cancelled,
|
||||
|
||||
/// <summary>Windows reported that the drive cannot be formatted.</summary>
|
||||
NotFormattable,
|
||||
|
||||
/// <summary>The last format attempt failed.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Windows "Format" dialog (SHFormatDrive), the only way Titano formats a card (BRIEF §8.6): the user confirms
|
||||
/// and starts the format in the OS dialog, quick format preselected.
|
||||
/// </summary>
|
||||
public static partial class FormatDialog
|
||||
{
|
||||
private const uint SHFMT_ID_DEFAULT = 0xFFFF;
|
||||
private const uint SHFMT_OPT_QUICK = 0x0; // no SHFMT_OPT_FULL: "Quick Format" stays checked
|
||||
private const uint SHFMT_ERROR = 0xFFFFFFFF;
|
||||
private const uint SHFMT_CANCEL = 0xFFFFFFFE;
|
||||
private const uint SHFMT_NOFORMAT = 0xFFFFFFFD;
|
||||
|
||||
/// <summary>Shows the modal dialog for <paramref name="driveLetter"/>. Call on the UI thread that owns <paramref name="ownerWindow"/>.</summary>
|
||||
/// <exception cref="ArgumentException">No owner window (the dialog requires one).</exception>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Not a drive letter.</exception>
|
||||
/// <exception cref="InvalidOperationException">The drive holds the running Windows installation.</exception>
|
||||
public static FormatDialogResult Show(nint ownerWindow, char driveLetter)
|
||||
{
|
||||
if (ownerWindow == 0) throw new ArgumentException("The format dialog needs an owner window.", nameof(ownerWindow));
|
||||
var letter = char.ToUpperInvariant(driveLetter);
|
||||
if (letter is < 'A' or > 'Z') throw new ArgumentOutOfRangeException(nameof(driveLetter), driveLetter, "Expected a drive letter A–Z.");
|
||||
var systemRoot = Path.GetPathRoot(Environment.SystemDirectory);
|
||||
if (!string.IsNullOrEmpty(systemRoot) && char.ToUpperInvariant(systemRoot[0]) == letter)
|
||||
throw new InvalidOperationException("The Windows system drive cannot be formatted.");
|
||||
|
||||
return SHFormatDrive(ownerWindow, (uint)(letter - 'A'), SHFMT_ID_DEFAULT, SHFMT_OPT_QUICK) switch
|
||||
{
|
||||
SHFMT_CANCEL => FormatDialogResult.Cancelled,
|
||||
SHFMT_NOFORMAT => FormatDialogResult.NotFormattable,
|
||||
SHFMT_ERROR => FormatDialogResult.Failed,
|
||||
_ => FormatDialogResult.Formatted,
|
||||
};
|
||||
}
|
||||
|
||||
[LibraryImport("shell32.dll")]
|
||||
private static partial uint SHFormatDrive(nint ownerWindow, uint drive, uint formatId, uint options);
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.Diagnostics;
|
||||
|
||||
namespace Titano.Core.Windows.Devices;
|
||||
|
||||
/// <summary>Event data for a volume that appeared or disappeared.</summary>
|
||||
public sealed class VolumeEventArgs(VolumeInfo volume) : EventArgs
|
||||
{
|
||||
public VolumeInfo Volume { get; } = volume;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detects cards and other import candidates (BRIEF §13): removable volumes, plus fixed volumes that hold a DCIM
|
||||
/// folder. A hidden window on a dedicated message-loop thread receives WM_DEVICECHANGE
|
||||
/// (DBT_DEVICEARRIVAL / DBT_DEVICEREMOVECOMPLETE with DEV_BROADCAST_VOLUME unit masks) and a 3-second
|
||||
/// <see cref="DriveInfo"/> poll on the same thread catches anything the broadcast missed. Both paths diff against
|
||||
/// the last snapshot, so each change is reported exactly once. Events are raised on the watcher thread.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The window is top-level but never shown, not message-only (HWND_MESSAGE): Windows broadcasts volume arrival
|
||||
/// and removal only to top-level windows, and message-only windows receive no broadcasts.
|
||||
/// </remarks>
|
||||
public sealed unsafe partial class RemovableVolumeWatcher : IDisposable
|
||||
{
|
||||
private const string WindowClassName = "Titano.RemovableVolumeWatcher";
|
||||
private const uint PollIntervalMilliseconds = 3000;
|
||||
private const nuint PollTimerId = 1;
|
||||
|
||||
private const uint WM_DESTROY = 0x0002;
|
||||
private const uint WM_CLOSE = 0x0010;
|
||||
private const uint WM_TIMER = 0x0113;
|
||||
private const uint WM_DEVICECHANGE = 0x0219;
|
||||
private const nint DBT_DEVICEARRIVAL = 0x8000;
|
||||
private const nint DBT_DEVICEREMOVECOMPLETE = 0x8004;
|
||||
private const uint DBT_DEVTYP_VOLUME = 0x2;
|
||||
private const uint WS_EX_TOOLWINDOW = 0x80;
|
||||
private const int GWLP_USERDATA = -21;
|
||||
private const int ERROR_CLASS_ALREADY_EXISTS = 1410;
|
||||
|
||||
private static readonly Lock ClassGate = new();
|
||||
private static bool s_classRegistered;
|
||||
|
||||
private readonly Dictionary<string, VolumeInfo> _known = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Lock _gate = new();
|
||||
private Thread? _thread;
|
||||
private nint _window;
|
||||
private GCHandle _self;
|
||||
private int _disposed;
|
||||
|
||||
/// <summary>A candidate volume was inserted or became ready.</summary>
|
||||
public event EventHandler<VolumeEventArgs>? VolumeArrived;
|
||||
|
||||
/// <summary>A known volume was removed (or its media was swapped; the new one then arrives).</summary>
|
||||
public event EventHandler<VolumeEventArgs>? VolumeRemoved;
|
||||
|
||||
/// <summary>Candidate volumes currently present (populated by <see cref="Start"/>, without events).</summary>
|
||||
public IReadOnlyList<VolumeInfo> Volumes
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return [.. _known.Values.OrderBy(v => v.RootPath, StringComparer.OrdinalIgnoreCase)];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True for volumes the import UI lists: removable media, or fixed media with a DCIM folder.</summary>
|
||||
public static bool IsCandidate(VolumeInfo volume) =>
|
||||
volume.DriveType == VolumeDriveType.Removable || (volume.DriveType == VolumeDriveType.Fixed && volume.HasDcim);
|
||||
|
||||
/// <summary>Takes the initial snapshot and starts watching; returns once the window exists.</summary>
|
||||
/// <exception cref="Win32Exception">The hidden window could not be created.</exception>
|
||||
public void Start()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed != 0, this);
|
||||
if (_thread is not null) throw new InvalidOperationException("The watcher is already running.");
|
||||
|
||||
using var ready = new ManualResetEventSlim();
|
||||
Win32Exception? failure = null;
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
_window = CreateHiddenWindow();
|
||||
Rescan(raiseEvents: false);
|
||||
}
|
||||
catch (Win32Exception ex)
|
||||
{
|
||||
failure = ex;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ready.Set();
|
||||
}
|
||||
if (failure is null) RunMessageLoop();
|
||||
})
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "Titano volume watcher",
|
||||
};
|
||||
thread.Start();
|
||||
ready.Wait();
|
||||
if (failure is not null)
|
||||
{
|
||||
thread.Join();
|
||||
throw failure;
|
||||
}
|
||||
_thread = thread;
|
||||
}
|
||||
|
||||
/// <summary>Stops watching and waits for the watcher thread (unless called from one of its event handlers).</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
if (_window != 0) PostMessageW(_window, WM_CLOSE, 0, 0);
|
||||
if (_thread is { } thread && thread != Thread.CurrentThread) thread.Join();
|
||||
}
|
||||
|
||||
private nint CreateHiddenWindow()
|
||||
{
|
||||
var instance = GetModuleHandleW(null);
|
||||
RegisterWindowClass(instance);
|
||||
var window = CreateWindowExW(WS_EX_TOOLWINDOW, WindowClassName, WindowClassName, 0, 0, 0, 0, 0, 0, 0, instance, 0);
|
||||
if (window == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
|
||||
_self = GCHandle.Alloc(this);
|
||||
SetWindowLongPtrW(window, GWLP_USERDATA, GCHandle.ToIntPtr(_self));
|
||||
if (SetTimer(window, PollTimerId, PollIntervalMilliseconds, 0) == 0)
|
||||
Log.Warning("devices", $"SetTimer failed (error {Marshal.GetLastPInvokeError()}); relying on WM_DEVICECHANGE only.");
|
||||
return window;
|
||||
}
|
||||
|
||||
private static void RegisterWindowClass(nint instance)
|
||||
{
|
||||
lock (ClassGate)
|
||||
{
|
||||
if (s_classRegistered) return;
|
||||
fixed (char* className = WindowClassName)
|
||||
{
|
||||
var windowClass = new WindowClass
|
||||
{
|
||||
Size = (uint)sizeof(WindowClass),
|
||||
WindowProcedure = (nint)(delegate* unmanaged<nint, uint, nint, nint, nint>)&WindowProcedure,
|
||||
Instance = instance,
|
||||
ClassName = className,
|
||||
};
|
||||
if (RegisterClassExW(&windowClass) == 0 && Marshal.GetLastPInvokeError() != ERROR_CLASS_ALREADY_EXISTS)
|
||||
throw new Win32Exception(Marshal.GetLastPInvokeError());
|
||||
}
|
||||
s_classRegistered = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void RunMessageLoop()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (GetMessageW(out var message, 0, 0, 0) > 0)
|
||||
{
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Normally a no-op (WM_QUIT follows WM_DESTROY); after a GetMessage failure it guarantees that no
|
||||
// callback can reach the handle once it is freed.
|
||||
DestroyWindow(_window);
|
||||
_self.Free();
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
private static nint WindowProcedure(nint window, uint message, nint wParam, nint lParam)
|
||||
{
|
||||
try
|
||||
{
|
||||
var handle = GetWindowLongPtrW(window, GWLP_USERDATA);
|
||||
if (handle != 0 && GCHandle.FromIntPtr(handle).Target is RemovableVolumeWatcher watcher)
|
||||
{
|
||||
switch (message)
|
||||
{
|
||||
case WM_DEVICECHANGE when (wParam == DBT_DEVICEARRIVAL || wParam == DBT_DEVICEREMOVECOMPLETE) && lParam != 0:
|
||||
var header = (DeviceBroadcastVolume*)lParam;
|
||||
if (header->DeviceType == DBT_DEVTYP_VOLUME) watcher.Refresh(header->UnitMask);
|
||||
return 1;
|
||||
case WM_TIMER when (nuint)wParam == PollTimerId:
|
||||
watcher.Rescan(raiseEvents: true);
|
||||
return 0;
|
||||
case WM_CLOSE:
|
||||
KillTimer(window, PollTimerId);
|
||||
DestroyWindow(window);
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
PostQuitMessage(0);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Nothing may unwind through a native callback.
|
||||
Log.Error("devices", "Volume watcher message handling failed", ex);
|
||||
}
|
||||
return DefWindowProcW(window, message, wParam, lParam);
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the drive letters named by a DEV_BROADCAST_VOLUME unit mask (bit 0 = A:).</summary>
|
||||
private void Refresh(uint unitMask)
|
||||
{
|
||||
for (var bit = 0; bit < 26; bit++)
|
||||
{
|
||||
if ((unitMask & (1u << bit)) == 0) continue;
|
||||
var root = $"{(char)('A' + bit)}:\\";
|
||||
Update(root, Read(root), raiseEvents: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Full poll: every local drive letter plus every previously known root.</summary>
|
||||
private void Rescan(bool raiseEvents)
|
||||
{
|
||||
var roots = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var drive in DriveInfo.GetDrives())
|
||||
{
|
||||
if (drive.DriveType is DriveType.Fixed or DriveType.Removable) roots.Add(drive.Name);
|
||||
}
|
||||
lock (_gate) roots.UnionWith(_known.Keys);
|
||||
foreach (var root in roots) Update(root, Read(root), raiseEvents);
|
||||
}
|
||||
|
||||
private static VolumeInfo? Read(string root) => VolumeInfo.TryRead(root) is { } volume && IsCandidate(volume) ? volume : null;
|
||||
|
||||
private void Update(string root, VolumeInfo? current, bool raiseEvents)
|
||||
{
|
||||
VolumeInfo? previous;
|
||||
lock (_gate)
|
||||
{
|
||||
_known.TryGetValue(root, out previous);
|
||||
if (current is null) _known.Remove(root);
|
||||
else _known[root] = current;
|
||||
}
|
||||
if (!raiseEvents) return;
|
||||
var sameVolume = previous is not null && current is not null && previous.Identity == current.Identity;
|
||||
if (previous is not null && !sameVolume) Raise(VolumeRemoved, previous);
|
||||
if (current is not null && !sameVolume) Raise(VolumeArrived, current);
|
||||
}
|
||||
|
||||
private void Raise(EventHandler<VolumeEventArgs>? handler, VolumeInfo volume)
|
||||
{
|
||||
try
|
||||
{
|
||||
handler?.Invoke(this, new VolumeEventArgs(volume));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error("devices", $"A volume event handler failed for {volume.RootPath}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>DEV_BROADCAST_VOLUME (the header's first three fields, then the unit mask and flags).</summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct DeviceBroadcastVolume
|
||||
{
|
||||
public uint Size;
|
||||
public uint DeviceType;
|
||||
public uint Reserved;
|
||||
public uint UnitMask;
|
||||
public ushort Flags;
|
||||
}
|
||||
|
||||
/// <summary>WNDCLASSEXW (80 bytes on x64).</summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct WindowClass
|
||||
{
|
||||
public uint Size;
|
||||
public uint Style;
|
||||
public nint WindowProcedure;
|
||||
public int ClassExtraBytes;
|
||||
public int WindowExtraBytes;
|
||||
public nint Instance;
|
||||
public nint Icon;
|
||||
public nint Cursor;
|
||||
public nint Background;
|
||||
public char* MenuName;
|
||||
public char* ClassName;
|
||||
public nint SmallIcon;
|
||||
}
|
||||
|
||||
/// <summary>MSG (48 bytes on x64).</summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Message
|
||||
{
|
||||
public nint Window;
|
||||
public uint Id;
|
||||
public nint WParam;
|
||||
public nint LParam;
|
||||
public uint Time;
|
||||
public int X;
|
||||
public int Y;
|
||||
public uint Private;
|
||||
}
|
||||
|
||||
[LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial nint GetModuleHandleW(string? moduleName);
|
||||
|
||||
[LibraryImport("user32.dll", SetLastError = true)]
|
||||
private static partial ushort RegisterClassExW(WindowClass* windowClass);
|
||||
|
||||
[LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
|
||||
private static partial nint CreateWindowExW(uint exStyle, string className, string windowName, uint style, int x, int y, int width, int height, nint parent, nint menu, nint instance, nint parameter);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool DestroyWindow(nint window);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial nint DefWindowProcW(nint window, uint message, nint wParam, nint lParam);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial int GetMessageW(out Message message, nint window, uint filterMin, uint filterMax);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool TranslateMessage(Message* message);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial nint DispatchMessageW(Message* message);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool PostMessageW(nint window, uint message, nint wParam, nint lParam);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial void PostQuitMessage(int exitCode);
|
||||
|
||||
[LibraryImport("user32.dll", SetLastError = true)]
|
||||
private static partial nuint SetTimer(nint window, nuint id, uint elapse, nint timerProcedure);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool KillTimer(nint window, nuint id);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial nint SetWindowLongPtrW(nint window, int index, nint value);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial nint GetWindowLongPtrW(nint window, int index);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace Titano.Core.Windows.Devices;
|
||||
|
||||
/// <summary>Outcome of <see cref="VolumeEjector.Eject"/>.</summary>
|
||||
public enum EjectResult
|
||||
{
|
||||
/// <summary>The volume was dismounted and the media ejected; the card can be removed.</summary>
|
||||
Ejected,
|
||||
|
||||
/// <summary>Another process holds files open on the volume; nothing was changed.</summary>
|
||||
InUse,
|
||||
|
||||
/// <summary>The drive is not a removable-media drive (fixed, network, unknown or no such letter).</summary>
|
||||
NotRemovable,
|
||||
|
||||
/// <summary>Windows refused to open, dismount or eject the volume.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Safe card removal (BRIEF §12.4): open <c>\\.\X:</c>, FSCTL_LOCK_VOLUME (retried while other handles close),
|
||||
/// FSCTL_DISMOUNT_VOLUME, IOCTL_STORAGE_MEDIA_REMOVAL (allow), IOCTL_STORAGE_EJECT_MEDIA. Blocks for up to about
|
||||
/// two seconds while retrying the lock; call it off the UI thread.
|
||||
/// </summary>
|
||||
public static unsafe class VolumeEjector
|
||||
{
|
||||
private const uint DRIVE_REMOVABLE = 2;
|
||||
private const uint DRIVE_CDROM = 5;
|
||||
private const int LockAttempts = 5;
|
||||
private static readonly TimeSpan LockRetryDelay = TimeSpan.FromMilliseconds(500);
|
||||
|
||||
public static EjectResult Eject(char driveLetter)
|
||||
{
|
||||
var letter = char.ToUpperInvariant(driveLetter);
|
||||
if (letter is < 'A' or > 'Z') throw new ArgumentOutOfRangeException(nameof(driveLetter), driveLetter, "Expected a drive letter A–Z.");
|
||||
if (VolumeNative.GetDriveType($"{letter}:\\") is not (DRIVE_REMOVABLE or DRIVE_CDROM)) return EjectResult.NotRemovable;
|
||||
|
||||
using var volume = VolumeNative.CreateFile(
|
||||
$@"\\.\{letter}:",
|
||||
VolumeNative.GENERIC_READ | VolumeNative.GENERIC_WRITE,
|
||||
VolumeNative.FILE_SHARE_READ | VolumeNative.FILE_SHARE_WRITE,
|
||||
0,
|
||||
VolumeNative.OPEN_EXISTING,
|
||||
0,
|
||||
0);
|
||||
if (volume.IsInvalid) return EjectResult.Failed;
|
||||
if (!Lock(volume)) return EjectResult.InUse;
|
||||
if (!Control(volume, VolumeNative.FSCTL_DISMOUNT_VOLUME)) return EjectResult.Failed;
|
||||
if (!AllowRemoval(volume)) return EjectResult.Failed;
|
||||
// Closing the handle afterwards releases the lock.
|
||||
return Control(volume, VolumeNative.IOCTL_STORAGE_EJECT_MEDIA) ? EjectResult.Ejected : EjectResult.Failed;
|
||||
}
|
||||
|
||||
private static bool Lock(SafeFileHandle volume)
|
||||
{
|
||||
for (var attempt = 1; attempt <= LockAttempts; attempt++)
|
||||
{
|
||||
if (Control(volume, VolumeNative.FSCTL_LOCK_VOLUME)) return true;
|
||||
if (attempt < LockAttempts) Thread.Sleep(LockRetryDelay);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Clears any media-removal lock; readers that do not implement the request count as unlocked.</summary>
|
||||
private static bool AllowRemoval(SafeFileHandle volume)
|
||||
{
|
||||
byte preventMediaRemoval = 0;
|
||||
if (VolumeNative.DeviceIoControl(volume, VolumeNative.IOCTL_STORAGE_MEDIA_REMOVAL, &preventMediaRemoval, sizeof(byte), null, 0, out _, 0)) return true;
|
||||
return Marshal.GetLastPInvokeError() is VolumeNative.ERROR_INVALID_FUNCTION or VolumeNative.ERROR_NOT_SUPPORTED;
|
||||
}
|
||||
|
||||
private static bool Control(SafeFileHandle volume, uint code) =>
|
||||
VolumeNative.DeviceIoControl(volume, code, null, 0, null, 0, out _, 0);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Titano.Core.Windows.Devices;
|
||||
|
||||
/// <summary>GetDriveTypeW results.</summary>
|
||||
public enum VolumeDriveType
|
||||
{
|
||||
Unknown = 0,
|
||||
NoRootDirectory = 1,
|
||||
Removable = 2,
|
||||
Fixed = 3,
|
||||
Remote = 4,
|
||||
CdRom = 5,
|
||||
RamDisk = 6,
|
||||
}
|
||||
|
||||
/// <summary>A mounted volume with the facts card import needs (BRIEF §12.4, §13).</summary>
|
||||
/// <param name="RootPath">Root with trailing separator, e.g. <c>E:\</c>.</param>
|
||||
/// <param name="Label">Volume label (may be empty).</param>
|
||||
/// <param name="FileSystem">File system name, e.g. exFAT.</param>
|
||||
/// <param name="SerialNumber">Volume serial number assigned at format time.</param>
|
||||
/// <param name="TotalBytes">Capacity in bytes.</param>
|
||||
/// <param name="FreeBytes">Free bytes available to the current user.</param>
|
||||
/// <param name="DriveType">Drive type reported by Windows.</param>
|
||||
/// <param name="HasDcim">A <c>DCIM</c> folder exists at the root (camera card).</param>
|
||||
public sealed record VolumeInfo(
|
||||
string RootPath,
|
||||
string Label,
|
||||
string FileSystem,
|
||||
uint SerialNumber,
|
||||
long TotalBytes,
|
||||
long FreeBytes,
|
||||
VolumeDriveType DriveType,
|
||||
bool HasDcim)
|
||||
{
|
||||
private const int MaxPath = 261;
|
||||
|
||||
public char DriveLetter => char.ToUpperInvariant(RootPath[0]);
|
||||
|
||||
/// <summary>Card identity <c>{serial:X8}-{label}-{capacity}</c> (BRIEF §13); stable across readers and drive letters.</summary>
|
||||
public string Identity => string.Create(CultureInfo.InvariantCulture, $"{SerialNumber:X8}-{Label}-{TotalBytes}");
|
||||
|
||||
/// <summary>Reads a volume; null when the root does not exist or holds no media (empty card reader).</summary>
|
||||
public static unsafe VolumeInfo? TryRead(string rootPath)
|
||||
{
|
||||
var root = NormalizeRoot(rootPath);
|
||||
var driveType = (VolumeDriveType)VolumeNative.GetDriveType(root);
|
||||
if (driveType is VolumeDriveType.Unknown or VolumeDriveType.NoRootDirectory) return null;
|
||||
|
||||
VolumeNative.SetThreadErrorMode(VolumeNative.SEM_FAILCRITICALERRORS, out var previousMode);
|
||||
try
|
||||
{
|
||||
var label = stackalloc char[MaxPath];
|
||||
var fileSystem = stackalloc char[MaxPath];
|
||||
if (!VolumeNative.GetVolumeInformation(root, label, MaxPath, out var serial, out _, out _, fileSystem, MaxPath)) return null;
|
||||
if (!VolumeNative.GetDiskFreeSpaceEx(root, out var free, out var total, out _)) return null;
|
||||
return new VolumeInfo(
|
||||
root,
|
||||
new string(label),
|
||||
new string(fileSystem),
|
||||
serial,
|
||||
(long)total,
|
||||
(long)free,
|
||||
driveType,
|
||||
Directory.Exists(Path.Combine(root, "DCIM")));
|
||||
}
|
||||
finally
|
||||
{
|
||||
VolumeNative.SetThreadErrorMode(previousMode, out _);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Every ready fixed or removable volume, enumerated through <see cref="DriveInfo"/> (network and optical drives are skipped).</summary>
|
||||
public static IReadOnlyList<VolumeInfo> ListLocal()
|
||||
{
|
||||
var volumes = new List<VolumeInfo>();
|
||||
foreach (var drive in DriveInfo.GetDrives())
|
||||
{
|
||||
if (drive.DriveType is not (System.IO.DriveType.Fixed or System.IO.DriveType.Removable)) continue;
|
||||
if (TryRead(drive.Name) is { } volume) volumes.Add(volume);
|
||||
}
|
||||
return volumes;
|
||||
}
|
||||
|
||||
/// <summary>"e:", "E:\" or "E:\DCIM" → "E:\".</summary>
|
||||
internal static string NormalizeRoot(string path)
|
||||
{
|
||||
var root = Path.GetPathRoot(path);
|
||||
if (string.IsNullOrEmpty(root)) throw new ArgumentException("The path has no root.", nameof(path));
|
||||
return root.EndsWith('\\') ? root.ToUpperInvariant() : root.ToUpperInvariant() + "\\";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace Titano.Core.Windows.Devices;
|
||||
|
||||
/// <summary>kernel32 volume and device-control entry points used by the Devices helpers.</summary>
|
||||
internal static unsafe partial class VolumeNative
|
||||
{
|
||||
public const uint GENERIC_READ = 0x80000000;
|
||||
public const uint GENERIC_WRITE = 0x40000000;
|
||||
public const uint FILE_SHARE_READ = 0x1;
|
||||
public const uint FILE_SHARE_WRITE = 0x2;
|
||||
public const uint OPEN_EXISTING = 3;
|
||||
public const uint SEM_FAILCRITICALERRORS = 0x1;
|
||||
|
||||
public const uint FSCTL_LOCK_VOLUME = 0x00090018;
|
||||
public const uint FSCTL_DISMOUNT_VOLUME = 0x00090020;
|
||||
public const uint IOCTL_STORAGE_MEDIA_REMOVAL = 0x002D4804;
|
||||
public const uint IOCTL_STORAGE_EJECT_MEDIA = 0x002D4808;
|
||||
|
||||
public const int ERROR_INVALID_FUNCTION = 1;
|
||||
public const int ERROR_NOT_SUPPORTED = 50;
|
||||
|
||||
[LibraryImport("kernel32.dll", EntryPoint = "GetDriveTypeW", StringMarshalling = StringMarshalling.Utf16)]
|
||||
public static partial uint GetDriveType(string rootPath);
|
||||
|
||||
[LibraryImport("kernel32.dll", EntryPoint = "GetVolumeInformationW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool GetVolumeInformation(
|
||||
string rootPath,
|
||||
char* volumeName,
|
||||
uint volumeNameSize,
|
||||
out uint serialNumber,
|
||||
out uint maximumComponentLength,
|
||||
out uint fileSystemFlags,
|
||||
char* fileSystemName,
|
||||
uint fileSystemNameSize);
|
||||
|
||||
[LibraryImport("kernel32.dll", EntryPoint = "GetDiskFreeSpaceExW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool GetDiskFreeSpaceEx(string directory, out ulong freeBytesAvailable, out ulong totalBytes, out ulong totalFreeBytes);
|
||||
|
||||
/// <summary>Per-thread error mode; SEM_FAILCRITICALERRORS stops "insert a disk" dialogs on empty card readers.</summary>
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool SetThreadErrorMode(uint newMode, out uint oldMode);
|
||||
|
||||
[LibraryImport("kernel32.dll", EntryPoint = "CreateFileW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
|
||||
public static partial SafeFileHandle CreateFile(string fileName, uint desiredAccess, uint shareMode, nint securityAttributes, uint creationDisposition, uint flagsAndAttributes, nint templateFile);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool DeviceIoControl(SafeFileHandle device, uint controlCode, void* inBuffer, uint inBufferSize, void* outBuffer, uint outBufferSize, out uint bytesReturned, nint overlapped);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Titano.Core.Windows.Devices;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Devices;
|
||||
|
||||
public sealed class VolumeTests
|
||||
{
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ListingIncludesTheSystemDriveWithItsSerial()
|
||||
{
|
||||
var systemRoot = Path.GetPathRoot(Environment.SystemDirectory)!;
|
||||
var volumes = VolumeInfo.ListLocal();
|
||||
var system = volumes.FirstOrDefault(v => string.Equals(v.RootPath, systemRoot, StringComparison.OrdinalIgnoreCase));
|
||||
if (system is null) Assert.Fail($"{systemRoot} missing from [{string.Join(", ", volumes.Select(v => v.RootPath))}]");
|
||||
Assert.NotEqual(0u, system!.SerialNumber);
|
||||
Assert.Greater(system.TotalBytes, 0);
|
||||
Assert.InRange(system.FreeBytes, 0, system.TotalBytes);
|
||||
Assert.Equal(VolumeDriveType.Fixed, system.DriveType);
|
||||
Assert.False(string.IsNullOrEmpty(system.FileSystem));
|
||||
Assert.True(Regex.IsMatch(system.Identity, "^[0-9A-F]{8}-.*-[0-9]+$"), system.Identity);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void MissingDriveLetterReadsAsNull()
|
||||
{
|
||||
var used = DriveInfo.GetDrives().Select(d => char.ToUpperInvariant(d.Name[0])).ToHashSet();
|
||||
var free = Enumerable.Range('D', 23).Select(c => (char)c).Where(c => !used.Contains(c)).ToArray();
|
||||
if (free.Length == 0) TestContext.Skip("Every drive letter is in use.");
|
||||
Assert.Null(VolumeInfo.TryRead($"{free[^1]}:\\"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void RootsAreNormalised()
|
||||
{
|
||||
Assert.Equal(@"E:\", VolumeInfo.NormalizeRoot("e:"));
|
||||
Assert.Equal(@"E:\", VolumeInfo.NormalizeRoot(@"E:\"));
|
||||
Assert.Equal(@"E:\", VolumeInfo.NormalizeRoot(@"e:\DCIM\100CANON"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdentityFollowsTheBriefFormat()
|
||||
{
|
||||
var card = new VolumeInfo(@"E:\", "EOS_DIGITAL", "exFAT", 0x3F2A9C11, 127_865_454_592, 1_000, VolumeDriveType.Removable, true);
|
||||
Assert.Equal("3F2A9C11-EOS_DIGITAL-127865454592", card.Identity);
|
||||
Assert.Equal('E', card.DriveLetter);
|
||||
Assert.Equal("0000000A--1024", (card with { SerialNumber = 10, Label = "", TotalBytes = 1024 }).Identity);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CandidatesAreRemovableOrCameraVolumes()
|
||||
{
|
||||
var card = new VolumeInfo(@"E:\", "", "exFAT", 1, 1, 1, VolumeDriveType.Removable, false);
|
||||
Assert.True(RemovableVolumeWatcher.IsCandidate(card));
|
||||
Assert.False(RemovableVolumeWatcher.IsCandidate(card with { DriveType = VolumeDriveType.Fixed }));
|
||||
Assert.True(RemovableVolumeWatcher.IsCandidate(card with { DriveType = VolumeDriveType.Fixed, HasDcim = true }));
|
||||
Assert.False(RemovableVolumeWatcher.IsCandidate(card with { DriveType = VolumeDriveType.Remote, HasDcim = true }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
[Timeout(30_000)]
|
||||
public void WatcherStartsAndStops()
|
||||
{
|
||||
using var watcher = new RemovableVolumeWatcher();
|
||||
watcher.Start();
|
||||
Assert.True(watcher.Volumes.All(RemovableVolumeWatcher.IsCandidate));
|
||||
Assert.Throws<InvalidOperationException>(watcher.Start);
|
||||
watcher.Dispose();
|
||||
Assert.Throws<ObjectDisposedException>(watcher.Start);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void EjectRefusesTheSystemDrive()
|
||||
{
|
||||
var letter = Path.GetPathRoot(Environment.SystemDirectory)![0];
|
||||
Assert.Equal(EjectResult.NotRemovable, VolumeEjector.Eject(letter));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EjectRejectsNonLetters() => Assert.Throws<ArgumentOutOfRangeException>(() => VolumeEjector.Eject('1'));
|
||||
|
||||
[Test]
|
||||
public void FormatDialogNeedsAnOwnerWindow() => Assert.Throws<ArgumentException>(() => FormatDialog.Show(0, 'E'));
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void FormatDialogRefusesTheSystemDrive()
|
||||
{
|
||||
var letter = Path.GetPathRoot(Environment.SystemDirectory)![0];
|
||||
// The guard runs before the dialog, so any non-null owner handle exercises it without showing UI.
|
||||
Assert.Throws<InvalidOperationException>(() => FormatDialog.Show(1, letter));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user