要在C#中偵測磁碟機的改變(新增/插入、移除/卸除)可以透過ManagementEventWatcher類別加上Windows提供的WMI來達到此功能,直接看程式碼內容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management; namespace DiskDetect { class Program { static void Main(string[] args) { ManagementEventWatcher watcher = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 or EventType = 3"); watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Query = query; watcher.Start(); Console.ReadLine(); } static void watcher_EventArrived(object sender, EventArrivedEventArgs e) { if (Convert.ToInt16(e.NewEvent.Properties["EventType"].Value) == 2) { Console.WriteLine("Disk Insert: " + e.NewEvent.Properties["DriveName"].Value); } else { Console.WriteLine("Disk Remove: " + e.NewEvent.Properties["DriveName"].Value); } } } } |
參考連結:
ManagementEventWatcher Class
Win32_VolumeChangeEvent
Keyword: How to detect disk state in C# language
沒有留言:
張貼留言