(WPF, Service) 删除注册表中的USB Enum值.

Task: 删除HKEY_LOCAL_MACHINESYSTEMCurrentControlSetEnumUSBVID_0XXX&PID_0XXX Key Tree

首先第一想到的使用PS Script来删除: 

Remove-Item -Path 'Registry::HKEY_LOCAL_MACHINESYSTEMCurrentControlSetEnumUSBVID_045E&PID_07DC'

 但是发现如果想删除USB Enum的话需要很高的权限,即使使用Admin权限,也遭到拒绝。

Remove-Item : Requested registry access is not allowed.
At D:Debug_LocalRemoveRegistry.ps1:2 char:1
+ Remove-Item -Path 'Registry::HKEY_LOCAL_MACHINESYSTEMCurrentControlSetEnumUS ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (HKEY_LOCAL_MACH...rolSetEnumUSB:String) [Remove-Item], SecurityException
    + FullyQualifiedErrorId : System.Security.SecurityException,Microsoft.PowerShell.Commands.RemoveItemCommand

随后开始考虑用C#程序来删除。同时安装为Windows Service来获取System权限,来删除之。

foreach (var registryKey in usbRegistryList)
            {
                string keyPath = string.Format(@"SYSTEMCurrentControlSetEnumUSB{0}", registryKey);
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyPath, true))
                {
                    if (key == null)
                    {
                        this.log.Append(this.GetCurrentDateTime()).Append(string.Format("The key {0} does not exist!", key)).Append(Environment.NewLine);  
                    }
                    else
                    {
                        try
                        {
                            foreach (var subKey in key.GetSubKeyNames())
                            {
                                key.DeleteSubKeyTree(subKey);
                                this.log.Append(this.GetCurrentDateTime()).AppendFormat("The sub key {0} is removed sucessfully!", subKey).Append(Environment.NewLine); 
                            }
                        }
                        catch (Exception ex)
                        {
                            this.log.AppendFormat("Error is found during removing key {0}. Details:{1}", key, ex.Message).Append(Environment.NewLine); 
                        }
                    }
                }
            }