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 of the Registry to 4 to disable USB (default: 3, that is, allow USB ).
Advantage: simple and easy to use.
Disadvantage: everyone on Earth knows it and it is easy to recognize it.
Suggestion: Use a timer or create a thread to lock the value.
Program code:
[Csharp]
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"; // USB high-capacity storage driver
RegistryKey openKey = regKey. OpenSubKey (keyPath, true );
OpenKey. SetValue ("Start", 3); // set the key-Value Pair (3) to enable USB (4) to disable
OpenKey. Close (); // Close the read/write stream of the registration list
Return true;
}
Catch (Exception ex)
{
Throw ex;
}
}
/// <Summary>
/// Disable USB through 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.
Disadvantage: You can only disable USB flash drives that have not been used on this computer. Www.2cto.com
Suggestion: Be sure to use the class member variable (module-level variable) to open the object when the file is exclusive. If the local variable is used, it will be automatically released by the hosting program, cannot achieve exclusive effect.
Program code:
Note: I put the following fs and fs1 object variables in the form as member variables of the Form class.
[Csharp]
Using System. IO;
Public FileStream fs = null;
Public FileStream fs1 = null;
// Open the file exclusively
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 );
Author: yangyuankp