Click here to Skip to main content
13,195,026 members (98,280 online)
Click here to Skip to main content
Add your own
alternative version


168 bookmarked
Posted 4 Jun 2009

Developing a USB Storage Device Protection Tool with C#

, 4 Jun 2009
Rate this:
Please Sign up or sign in to vote.
USB storage policy management, Registry editing, password protection, and hashing.


USB storage devices (flash drives, USB sticks etc.) offer many advantages for us. However, at the same time, they cause security problems because it is easy to copy a lot of files to a tiny USB memory in a few seconds. We might have some secure data on our PC which we do not want other users to copy through the USB. Therefore, we many need to define a USB storage policy to make USB drives write protected or not to be accessed through the system.


Windows XP with SP2 or later Operating Systems provide soft protection of USB ports. This feature can be enabled through the Registry Editor. Under HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\StorageDevicePolicies, there is a DWORD value named WriteProtect. Setting this value to 1 makes USB drives write protected.

We may want to completely disable USB drives. For this, the Start value in the following Registry key needs to be set to 4: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\UsbStor.

The Program

For many users, dealing with Registry keys is a boring job. A utility software developed for this job will be very useful.

Let’s develop our own application having the following functionalities:

  1. Define a USB storage devices access mode (Full Access/ Read Only / Disabled)
  2. Enable / Disable the Registry editor
  3. Provide password protection for configuration

The second functionality is needed because otherwise the configuration can be discarded easily by other people with the help of the Registry Editor (Regedit). And the third functionality, password protection, will prevent configuration change attempts of unauthorized users.

In Visual Studio 2005/2008, create a new Windows Forms Application project. Rename the empty form to frmMain. To make use of the Windows Registry functionality within our C# program, we need to add the following line to the beginning of our code:

using Microsoft.Win32;

Before making any changes in the configuration, it is good to know the current configuration. To achieve that, define the following methods and call them during the Load event of frmMain:

private void frmMain_Load(object sender, EventArgs e)

Define the CheckPasswordStatus() method as follows:

private void CheckPasswordStatus()
    Program.strPwdFilePath += "\\usbpolicy.pwd";
    if (File.Exists(Program.strPwdFilePath))
             StreamReader fsPwdFile =
                      new StreamReader(
                            new FileStream(
                               FileMode.Open, FileAccess.Read));
             string pwd = fsPwdFile.ReadToEnd();
             if (String.IsNullOrEmpty(pwd) == false)
             Program.isPwdEnabled = true;
        catch { }
        Program.isPwdEnabled = false;

In this code segment, you can see that there are two global variables, a string named strPwdFilePath, and a boolean variable named isPwdEnabled . These variables are defined in the Program.cs file and are accessible to all the forms in our application. This is because we need to access these variables again in two other forms related to password protection. To learn the status of USB write protection, we need to read the WriteProtect value under the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\StorageDevicePolicies key with the help of the following code defined in the body of the USB_getStatus() method:

RegistryKey key;
    key = Registry.LocalMachine.OpenSubKey
    if (System.Convert.ToInt16(key.GetValue("WriteProtect", null)) == 1)
        USB_radio_ReadOnly.Checked = true;
        USB_radio_FullAccess.Checked = true;
catch (NullReferenceException )
    key = Registry.LocalMachine.OpenSubKey
             ("SYSTEM\\CurrentControlSet\\Control", true);
catch( Exception ) {}

As you can see, the code is written in try and catch blocks because the absence of the StorageDevicePolicies key will cause a NullReferenceExcetion. In this case, we need to catch the exception and create the key. We are not done yet. The Start value under the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\UsbStor key also needs to be checked. So, continue with the USB_getStatus() method with the following lines of code:

    key = Registry.LocalMachine.OpenSubKey
    if (System.Convert.ToInt16(key.GetValue("Start", null)) == 4)
       USB_radio_Disabled.Checked = true;
catch ( NullReferenceException )
    key = Registry.LocalMachine.OpenSubKey
             ("SYSTEM\\CurrentControlSet\\Services", true);
    key = Registry.LocalMachine.OpenSubKey
            ("SYSTEM\\CurrentControlSet\\Services\\UsbStor", true);
    key.SetValue("Type", 1, RegistryValueKind.DWord);
    key.SetValue("Start", 3, RegistryValueKind.DWord);
    key.SetValue("ImagePath", "system32\\drivers\\usbstor.sys", 
    key.SetValue("ErrorControl", 1, RegistryValueKind.DWord);
    key.SetValue("DisplayName", "USB Mass Storage Driver",

catch( Exception ) {}

To enable write protection, define the following method:

void USB_enableWriteProtect()
    RegistryKey key = 
            ("SYSTEM\\CurrentControlSet\\Control\\StorageDevicePolicies", true);
    if (key == null)
       key = Registry.LocalMachine.OpenSubKey
          ("SYSTEM\\CurrentControlSet\\Control\\StorageDevicePolicies", true);
       key.SetValue("WriteProtect", 1, RegistryValueKind.DWord);
    else if (key.GetValue("WriteProtect") != (object)(1))
       key.SetValue("WriteProtect", 1, RegistryValueKind.DWord);

To disable write protection, use the following method:

void USB_disableWriteProtect()
    RegistryKey key =
    if (key != null)
       key.SetValue("WriteProtect", 0, RegistryValueKind.DWord);

To disable USB storage devices (make them not available to use):

void USB_disableAllStorageDevices()
    RegistryKey key =
    if (key != null)
       key.SetValue("Start", 4, RegistryValueKind.DWord);

To enable USB storage services:

void USB_enableAllStorageDevices()
    RegistryKey key = 
          ("SYSTEM\\CurrentControlSet\\Services\\UsbStor", true);
    if (key != null)
       key.SetValue("Start", 3, RegistryValueKind.DWord);

To disable Regedit:

private void REG_DisableRegedit()
    RegistryKey key = 
           ("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true);
    key.SetValue("DisableRegistryTools", 1, RegistryValueKind.DWord);

To enable Regedit:

private void REG_EnableRegedit()
    RegistryKey key = 
           ("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true);
    key.SetValue("DisableRegistryTools", 0, RegistryValueKind.DWord);

The third functionality of our program is password protection to prevent unauthorized access to configuration. To achieve this, we will design two others forms. In the first form, we define, change, or remove password.


In the second one, we will just do a password confirmation.


There are several ways to store the password. Our approach will be to hash the password string first and then store it in a file in the Windows directory.

To hash the password string, we will use the following method:

public static string MD5Hash(string str)
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    byte[] data = System.Text.Encoding.ASCII.GetBytes( str );
    data = md5.ComputeHash(data);
    string md5Hash = System.Text.Encoding.ASCII.GetString(data);
    return md5Hash;

Since this method is used by more than one form, it is good to make it static and define it in a static class in which common methods are defined.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Turkey Turkey
Borned in Malatya, TURKEY. Graduated from Department of Computer Engineering, Eastern Mediterranean University, T.R.N.C

Currently, PhD student-Graduate Research Assistant in Computer Sciences Department at UW-Madison.

You may also be interested in...


Comments and Discussions

Questionhow to disable USB based mass storage devices except a few USB based external hard disk based on its serial number Pin
Deepeshonly5-Apr-16 6:59
memberDeepeshonly5-Apr-16 6:59 
QuestionDebug Target Is Missing? Pin
Member 1041097224-Dec-15 21:01
memberMember 1041097224-Dec-15 21:01 
Questioncool Pin
Samir Ahmed17-Aug-15 11:11
memberSamir Ahmed17-Aug-15 11:11 
Generalhelp Pin
Member 111953041-Nov-14 9:32
memberMember 111953041-Nov-14 9:32 
QuestionNot working with windows 7 Pin
rbmitrb25-Aug-14 20:14
memberrbmitrb25-Aug-14 20:14 
AnswerRe: Not working with windows 7 Pin
Member 1021418331-Jul-15 3:53
professionalMember 1021418331-Jul-15 3:53 
Questioneasy Pin
Member 1075141815-Apr-14 7:38
memberMember 1075141815-Apr-14 7:38 
QuestionUsb enabled Automaticly after few day!!! Pin
Pouya474-Dec-13 21:48
memberPouya474-Dec-13 21:48 
GeneralMy vote of 4 Pin
Mic8-Aug-13 13:52
memberMic8-Aug-13 13:52 
Questionspecific drive write protected? Pin
Bikar1112-Jul-13 19:34
memberBikar1112-Jul-13 19:34 
GeneralMy vote of 5 Pin
Gun Gun Febrianza24-May-13 2:30
member Gun Gun Febrianza24-May-13 2:30 
QuestionWhat about Write only? Pin
farhanmirzaaa29-Jan-13 3:02
memberfarhanmirzaaa29-Jan-13 3:02 
QuestionFile damage Pin
lailailaihou15-Nov-12 20:38
memberlailailaihou15-Nov-12 20:38 
QuestionUser rights? Pin
mr_iq732-Jul-12 3:22
membermr_iq732-Jul-12 3:22 
QuestionDeny execution? Pin
mr_iq732-Jul-12 3:20
membermr_iq732-Jul-12 3:20 
Questionquestion2 Pin
aliprogrammer28-Apr-12 20:52
memberaliprogrammer28-Apr-12 20:52 
Questionquestion Pin
aliprogrammer28-Apr-12 20:44
memberaliprogrammer28-Apr-12 20:44 
GeneralMy Vote of 5 Pin
RaviRanjankr8-Dec-11 4:34
memberRaviRanjankr8-Dec-11 4:34 
Generalusb connection Pin
parastoo_8121419-Feb-11 1:17
memberparastoo_8121419-Feb-11 1:17 
GeneralMy vote of 5 Pin
Aslam_Iqbal10-Jan-11 8:24
memberAslam_Iqbal10-Jan-11 8:24 
GeneralMy vote of 4 Pin
anirban_sinha30-Dec-10 22:39
memberanirban_sinha30-Dec-10 22:39 
GeneralVery Useful Tool for Me Pin
Sunasara Imdadhusen24-Dec-10 23:05
memberSunasara Imdadhusen24-Dec-10 23:05 
I always appreciate your work.

Please keep it upThumbs Up | :thumbsup:

My vote is 5


sunaSaRa Imdadhusen
+91 99095 44184
+91 02767 284464

GeneralMy vote of 5 Pin
Sunasara Imdadhusen24-Dec-10 23:04
memberSunasara Imdadhusen24-Dec-10 23:04 
GeneralUSB_Policy.exe.manifest Pin
aditya_ingle10-Sep-10 5:22
memberaditya_ingle10-Sep-10 5:22 
GeneralGod,help, plz!!! Pin
small23-Sep-10 7:31
membersmall23-Sep-10 7:31 
GeneralRe: God,help, plz!!! Pin
Ozcan ILIKHAN4-Sep-10 13:50
memberOzcan ILIKHAN4-Sep-10 13:50 
GeneralRe: God,help, plz!!! Pin
aliprogrammer28-Apr-12 21:08
memberaliprogrammer28-Apr-12 21:08 
GeneralMy vote of 5 Pin
birthfuture26-Jul-10 11:32
memberbirthfuture26-Jul-10 11:32 
Questionwhat the benefit of usbstor.sys Pin
zaed19-Jul-10 9:16
memberzaed19-Jul-10 9:16 
AnswerRe: what the benefit of usbstor.sys Pin
Ozcan ILIKHAN4-Sep-10 13:52
memberOzcan ILIKHAN4-Sep-10 13:52 
GeneralNot compatable with windows vista/7 Pin
Crazyd2279-Feb-10 4:41
memberCrazyd2279-Feb-10 4:41 
GeneralRe: Not compatable with windows vista/7 Pin
Hassan3D29-Mar-10 2:41
memberHassan3D29-Mar-10 2:41 
Question.... Pin
manali2426-Aug-09 0:11
membermanali2426-Aug-09 0:11 
AnswerRe: .... Pin
Aslam_Iqbal10-Jan-11 8:53
memberAslam_Iqbal10-Jan-11 8:53 
Generalhelp plz. Pin
manali2420-Aug-09 20:05
membermanali2420-Aug-09 20:05 
GeneralRe: help plz. Pin
Ozcan ILIKHAN20-Aug-09 22:13
memberOzcan ILIKHAN20-Aug-09 22:13 
GeneralPls. Help Me Pin
rikimaruz0917-Jul-09 18:39
memberrikimaruz0917-Jul-09 18:39 
GeneralRe: Pls. Help Me Pin
Ozcan ILIKHAN18-Jul-09 21:13
memberOzcan ILIKHAN18-Jul-09 21:13 
Generaldisable usb Pin
Power-x25-Jun-09 8:15
memberPower-x25-Jun-09 8:15 
GeneralRe: disable usb Pin
Ozcan ILIKHAN26-Jun-09 1:34
memberOzcan ILIKHAN26-Jun-09 1:34 
GeneralRe: disable usb Pin
stanliritche28-Apr-10 3:48
memberstanliritche28-Apr-10 3:48 
Generalregistry access policy Pin
Alex Cohn9-Jun-09 1:28
memberAlex Cohn9-Jun-09 1:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171018.2 | Last Updated 5 Jun 2009
Article Copyright 2009 by Ozcan ILIKHAN
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid