检测网络驱动器挂载wmi
问题描述:
如何使用wmi检测网络驱动器挂载事件?我主要感兴趣的是像Win32_VolumeChangeEvent这样的网络驱动器。检测网络驱动器挂载wmi
_eventWatcher = new ManagementEventWatcher("SELECT * FROM Win32_VolumeChangeEvent");
_eventWatcher.EventArrived += (o, args) =>
{switch(args.NewEvent["EventType"].ToString()[0])
{
case '2':
//mount
Debug.WriteLine(args.NewEvent["DriveName"]);
break;
case '3':
//unmount
break;
}
};
_eventWatcher.Start();
在此先感谢。
答
您可以使用此查询(我使用PowerShell进行快速测试,但你可以很容易地转换成C#)
$query = "SELECT * FROM __instanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=4"
Register-WMIEvent -Query $query -Action {$global:a=$Args[0];$global:b=$Args[1];write-host "done" }
Id Name State HasMoreData Location Command
-- ---- ----- ----------- -------- -------
14 f2c5223d-3ae... NotStarted False $global:a=$Args[0];$gl...
PS C:\> net use
Les nouvelles connexions seront mémorisées.
La liste est vide.
PS C:\> net use o: \\jpbhpp2\c$
La commande s'est terminée correctement.
PS C:\> done
PS C:\> $a
Scope : System.Management.ManagementScope
Query : System.Management.EventQuery
Options : System.Management.EventWatcherOptions
Site :
Container :
PS C:\> $b
NewEvent Context
-------- -------
System.Management.ManagementBaseObject {}
PS C:\> $b.NewEvent
__GENUS : 2
__CLASS : __InstanceCreationEvent
__SUPERCLASS : __InstanceOperationEvent
__DYNASTY : __SystemClass
__RELPATH :
__PROPERTY_COUNT : 3
__DERIVATION : {__InstanceOperationEvent, __Event, __IndicationRelated, __SystemClass}
__SERVER : WM2008R2ENT
__NAMESPACE : //./root/CIMV2
__PATH :
SECURITY_DESCRIPTOR :
TargetInstance : System.Management.ManagementBaseObject
TIME_CREATED : 129670237461553750
PS C:\> $b.NewEvent.TargetInstance
__GENUS : 2
__CLASS : Win32_LogicalDisk
__SUPERCLASS : CIM_LogicalDisk
__DYNASTY : CIM_ManagedSystemElement
__RELPATH : Win32_LogicalDisk.DeviceID="O:"
__PROPERTY_COUNT : 40
__DERIVATION : {CIM_LogicalDisk, CIM_StorageExtent, CIM_LogicalDevice, CIM_LogicalElement...}
__SERVER : WM2008R2ENT
__NAMESPACE : root\CIMV2
__PATH : \\WM2008R2ENT\root\CIMV2:Win32_LogicalDisk.DeviceID="O:"
Access : 0
Availability :
BlockSize :
Caption : O:
Compressed : False
ConfigManagerErrorCode :
ConfigManagerUserConfig :
CreationClassName : Win32_LogicalDisk
Description : Connexion réseau
DeviceID : O:
DriveType : 4
ErrorCleared :
ErrorDescription :
ErrorMethodology :
FileSystem : NTFS
FreeSpace : 36223737856
InstallDate :
LastErrorCode :
MaximumComponentLength : 255
MediaType : 0
Name : O:
NumberOfBlocks :
PNPDeviceID :
PowerManagementCapabilities :
PowerManagementSupported :
ProviderName : \\jpbhpp2\c$
Purpose :
QuotasDisabled : True
QuotasIncomplete : False
QuotasRebuilding : False
Size : 500000878592
Status :
StatusInfo :
SupportsDiskQuotas : True
SupportsFileBasedCompression : True
SystemCreationClassName : Win32_ComputerSystem
SystemName : WM2008R2ENT
VolumeDirty :
VolumeName :
VolumeSerialNumber : 96B00597
答
您可以监听任何VolumeChangeEvent,然后只检查驱动器是一个网络驱动器:
DriveInfo info = new DriveInfo(driveLetter);
if(info.DriveType == DriveType.Network)
//DoSomething
答
对于网络共享监控,您可以使用RegistryKeyChangeEvent。
- RegistryKeyChangeEvent位于root \ default。 (不是root \ CIMV2,默认使用.net)
- 挂载点信息存储在注册表中:HKEY_CURRENT_USER \ Network。但是,RegistryKeyChangeEvent无法监视HKEY_CURRENT_USER(令人失望)。因此,您必须通过以下方式访问它:HKEY_USERS \ S-1-5-18 \ Network(其中S-1-5-18是您用户的SID)。
- 要确定您的用户的SID,请检查followind注册表路径:HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion \ ProfileList。
最后的代码应该是这样的:
Dim m As New ManagementEventWatcher("root\default", "SELECT * FROM RegistryKeyChangeEvent WHERE Hive=""HKEY_USERS"" AND KeyPath=""<YOUR USER SID HERE>\\Network""")
AddHandler m.EventArrived, AddressOf <YOUR HANDLER FUNCTION>
m.Start()
该代码会在每次用户安装或卸除网络共享时调用处理函数。
看来它没有捕捉到它。我不知道为什么。 – user629926
你如何捕捉它? – ChrFin
快速搜索:您的代码无法检测到网络驱动器(请参阅http://*.com/questions/8188876/detect-drive-mount-event-in-c-sharp)。可以试试这个:http://www.codeproject.com/KB/system/DriveDetector.aspx。 – ChrFin