方法一:通过修改注册表禁用USB
原理:只要把注册表HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\USBSTOR路径下的Start值改成4即可禁用USB(默认为3,即允许USB)。
优点:简单易行。
缺点:地球人都知道,很容易识破。
建议:用一个timer或者创建一个线程,来锁定这个值。
程序代码:
- using Microsoft.Win32;
-
-
-
-
-
- public bool RegToRunUSB()
- {
- try
- {
- RegistryKey regKey = Registry.LocalMachine;
- string keyPath = @"SYSTEM\CurrentControlSet\Services\USBSTOR";
- RegistryKey openKey = regKey.OpenSubKey(keyPath, true);
- openKey.SetValue("Start", 3);
- openKey.Close();
- return true;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
-
-
-
-
-
- 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;
- }
- }
方法二:通过独占USB驱动文件禁用USB
原理:如果U盘第一次在某个电脑上使用,电脑会自动安装该U盘的驱动信息,修改C:\Windows\inf\usbstor.inf和C:\Windows\inf\usbstor.PNF这两个文件。假如我们用C#程序以独占的形式打开他们,那么Windows便无法修改这两个文件,U盘驱动安装不上自然无法使用。
优点:简单易行,不容易识破。
缺点:只能禁用未在该电脑上使用过的U盘。
建议:一定要注意独占的时候文件打开对象要用类的成员变量(也就是模块级变量),如果用局部变量,会自动被托管程序释放,达不到独占的效果。
程序代码:
注:以下fs和fs1对象变量我是放在了窗体中,作为窗体类的成员变量。
- using System.IO;
-
- public FileStream fs = null;
- public FileStream fs1 = null;
-
-
- 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);