Method 1: Disable USB by modifying the Registry
Principle:You only need to change the start value in the HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services \ usbstor path to 4 to disable USB (3 by default ).
Advantages:Easy to use.
Disadvantages:Everyone on Earth knows that it is easy to understand.
Suggestion:Use a timer or create a thread to lock this value.
ProgramCode:
Using Microsoft. win32; /// <summary> /// Enable USB through the registry /// </Summary> /// <returns> </returns> Public bool regtorunusb () {try {registrykey regkey = registry. localmachine; // read the registration list HKEY_LOCAL_MACHINE string keypath = @ "SYSTEM \ CurrentControlSet \ Services \ usbstor"; // The registrykey openkey = regkey of the USB high-capacity storage driver. opensubkey (keypath, true); openkey. setvalue ("START", 3); // set the key-Value Pair (3) to enable USB (4) to disable openkey. close (); // close the registration list read/write stream return true;} catch (exception ex) {Throw ex ;}} /// <summary> /// disable USB through the registry /// </Summary> /// <returns> </returns> Public bool regtostopusb () {try {registrykey regkey = registry. localmachine; string keypath = @ "SYSTEM \ CurrentControlSet \ Services \ usbstor"; registrykey openkey = regkey. opensubkey (keypath, true); openkey. setvalue ("START", 4); openkey. close (); Return true;} catch (exception ex) {Throw ex ;}}
Method 2: Disable USB through an exclusive USB driver File
Principle:If the USB flash drive is used on a computer for the first time, the computer will automatically install the drive information of the USB flash drive and modify c: \ windows \ INF \ usbstor. INF and c: \ windows \ INF \ usbstor. PNF files. If we use the C # program to open them in an exclusive form, Windows will not be able to modify these two files, and the U disk driver cannot be installed and cannot be used.
Advantages:Simple and easy to understand.
Disadvantages:You can only disable USB flash drives that have not been used on this computer.
Suggestion:Be sure to use the class member variable (module-level variable) to open the object during the exclusive operation. If the local variable is used, it will be automatically released by the hosting program, and the exclusive effect will not be reached.
Program code:
Note:The following FS and fs1 object variables are stored in the form and used as member variables of the Form class.
Using system. io; Public filestream FS = NULL; Public filestream fs1 = NULL; // open the file FS = new filestream ("C: \ WINDOWS \ INF \ usbstor. INF ", filemode. open, fileaccess. read, fileshare. none); fs1 = new filestream ("C: \ WINDOWS \ INF \ usbstor. PNF ", filemode. open, fileaccess. read, fileshare. none );