Friday, January 4, 2013

Disable USB drives using C#

The C# code below is capable of enabling/disabling the USB drives of computers running in Windows XP, Windows Vista or Windows 7.
using Microsoft.Win32;

namespace USB
{
    class Program
    {
        enum Permission { Allow = 3, Deny = 4 };

        static void Main(string[] args)
        {            
            RegistryKey key;

            key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\USBSTOR", true);

            key.SetValue("Start", (int)Permission.Deny);
        }
    }
}
*** Using the Microsoft.Win32 namespace you will be able to retrieve and modify the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\USBSTOR registry key, Setting the value data of Start to 4 will disable the USB drives of the PC.

1 comment:

  1. I need to disable USB port of the computer using c# ..

    below is the solution which is working for 32 bit windows but not working 64 bit ... I need a same function which can do the same thing for 64 bit ....

    //disable USB storage...
    Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR", "Start", 4, Microsoft.Win32.RegistryValueKind.DWord);

    //enable USB storage...
    Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR", "Start", 3, Microsoft.Win32.RegistryValueKind.DWord);

    i can read the value on windows 64 bit but can not write the value....
    RegistryKey registryKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);

    Console.WriteLine("registryKey" + registryKey);


    registryKey = registryKey.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\USBSTOR");
    Object val = registryKey.GetValue("Start");
    Console.WriteLine("The val is:" + val);
    here i am getting the current val which is set ...
    but when i try to open in write mode...
    registryKey = registryKey.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\USBSTOR", true);
    and try to set a value 4 to disable it cant work...
    registryKey.SetValue("Start", 4);

    ReplyDelete