4
我写了一个c#程序来查找新插入的USB驱动器和它的驱动器号。现在,当我运行这个程序时,我得到了插入事件并且无法得到驱动器盘符。任何人都可以建议我做一个想法吗?如何在c#中新插入USB驱动器号?
代码
static void Main(string[] args)
{
ManagementEventWatcher mwe_creation; //Object creation for 'ManagementEventWatcher' class is used to listen the temporary system event notofications based on specific query.
WqlEventQuery q_creation = new WqlEventQuery(); //Represents WMI(Windows Management Instrumentation) event query in WQL format for more information goto www.en.wikipedia.org/wiki/WQL
q_creation.EventClassName = "__InstanceCreationEvent";// Sets the eventclass to the query
q_creation.WithinInterval = new TimeSpan(0, 0, 2); // Setting up the time interval for the event check(here, it is 2 Seconds)
q_creation.Condition = @"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'"; //Sets which kind of event to be notified
mwe_creation = new ManagementEventWatcher(q_creation); //Initializing new instance
mwe_creation.EventArrived += new EventArrivedEventHandler(USBEventArrived_Creation);//Calling up 'USBEventArrived_Creation' method when the usb storage plug-in event occured
mwe_creation.Start(); // Starting to listen to the system events based on the given query
while (true) ;
}
static void USBEventArrived_Creation(object sender, EventArrivedEventArgs e){
Console.WriteLine("USB PLUGGED IN!");
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
foreach (var property in instance.Properties)
{
if (property.Name == "Name")
Console.WriteLine(property.Name + " = " + property.Value);
}
}
你尝试过这种无功机= DriveInfo.GetDrives() 。凡(驱动=> drive.IsReady && drive.DriveType == DriveType.Removable); – rashfmnb
这将挑选目前在系统中的所有可移动驱动器 –
看看这个satckoverflow链接它有太多的信息http://stackoverflow.com/questions/6003822/how-to-detect-a-usb-drive-已被插入 – rashfmnb