Search code examples
c#usbregistryconsole-application

I want to block USB Port using C# console application


I am trying to make a simple program that can modify windows registry through code.I have tried adding an Application Manifest File to provide admin privileges to the code but nothing seems to work.

    try
        { 
            RegistryKey MyKey = Registry.LocalMachine.OpenSubKey("/SYSTEM/CurrentControlSet/Services/USBSTOR", true);
         //the control jumps to catch after the above line.
            MyKey.SetValue("Start", "4", RegistryValueKind.DWord);
            System.Console.WriteLine("Port locked");
            System.Console.ReadKey();
        }//throws a nullvaluerefrence exception
        catch
        {
            System.Console.WriteLine("There was an error");
            System.Console.ReadKey();
        }

Solution

  • MyKey.SetValue has an invalid parameter. string cannot be converted to int.

    MyKey.SetValue("Start", "4", RegistryValueKind.DWord);
    

    Change the code to:

    MyKey.SetValue("Start", 0x4, RegistryValueKind.DWord);