A very simple C# program to change a registry value

Yet another grace-be-damned solution: I needed a C# .exe file that when run changes the value of one specific registry key to a hard coded value specified within the code of the .exe file.

I make no excuses for the lack of elegance or thoroughness, but pass it on for what it is – a truly basic applet that does one thing, and if for whatever reason it doesn’t succeed it, it will throw a generic error message.  Opposed to a lot of samples I found on the web,  this one  should work as is, and should be fairly extendable- say if you wanted to check for specific errors, or provide confirmation boxes indicating existing registry key values and what it will change to before you run it, and so forth.

If you’re like me, and asked a bunch of incredulous questions such as ‘why do you want to do this?’ then look at the bottom of the post for the dirt.

For those who were in a similar boat (the ‘just get it done’ boat), here’s the code:

using System;
using System.Windows.Forms;
using Microsoft.Win32;

namespace SwitchRegistryKey
static class Program
static void Main()
RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\MyTestKey", true);
myKey.SetValue("MyTestSubKey", "3", RegistryValueKind.DWord);
MessageBox.Show("The registry key has been switched","Title Goes Here");
MessageBox.Show("There was an error switching the registry key","Title Goes Here");


  • Registry.LocalMachine means it is looking in ComputerHKEY_LOCAL_MACHINE
  • Make sure you escape your paths as \ inside your C# code.  That is use SOFTWARE\MyTestKey as opposed to SOFTWAREMyTestKey
  • RegistryValueKind : DWord is just one of the types available, such as String.  Make sure you choose the appropriate kind for the key you are updating
  • The try statement only updates an existing key.  If the program cant find that key, or can’t update it for any reason it immediately will throw the MessageBox message in the catch statement.
  • To make a distributable, create a new C# project
  • save this as the program.cs code
  • add a nifty .ico on the project properties page
  • build the program
  • grab the .exe file (with it’s nifty .ico file you added) from your debug folder

So yea – I was approached by someone at work who needed this out ‘today’.  Apparently there was a buggy Office add-in that we rolled out that constantly keeps getting ‘disabled’ when it crashes.  When it’s disabled, there’s a specific key that flips from 3 to 2, and in order to re-enable it for ‘testing purposes’ they wanted to distribute an exe file users could double click from their desktop.

Yea ok, try fixing the buggy addin instead of asking me to compensate with this app- but seeing as it’s the real world, this interim solution will have to make do until the real devs (not some Project Manager) has free time.

Leave a Reply