Search code examples
c#registry

how to insert any value to registry using C#?


I have to insert this to the registry:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnConnect]
"AutoRun"="d:\\MyFolder\\MyProgram.exe"

How would I do this in C#?


Solution

  • Something like this:

    string name = @"SOFTWARE\Microsoft\Windows CE Services\AutoStartOnConnect";
    using (RegistryKey key = Registry.LocalMachine.OpenSubKey(name, true))
    {
        if (key == null)
        {
            // Whatever you want to do if the key isn't found
        }
        else
        {
            key.SetValue("AutoRun", @"d:\MyFolder\MyProgram.exe");
        }
    }
    

    If you use CreateSubKey instead of OpenSubKey, that will create it if it doesn't already exist (or open it for write otherwise) - but I suspect that in most cases, if the key doesn't exist then that indicates the rest of the system isn't in an appropriate state for your app.