Michael Tot Korsgaard Michael Tot Korsgaard - 16 days ago 6
C# Question

Running .bat file whenever a user is logged in

I want a

.bat
file to run whenever the machine starts (or alternatively whenever a user is signed in)

For this I've made this piece of code:

string subKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
RegistryKey key;
if (ClientSystem.Is64BitOperatingSystem)
{
key = RegistryKey.OpenBaseKey(
RegistryHive.LocalMachine,
RegistryView.Registry64
).OpenSubKey(subKey);
}
else
{
key = Registry.LocalMachine.OpenSubKey(subKey, true);
}
key.SetValue("websocket", @"c:\websocket\run.bat"); // error here


when running this I get an error telling me that I don't have permission change the file.

As @Tolanj mentions it might be an idea to add the actual error message:


Der kan ikke skrives til registreringsdatabasenøglen.


Which would translate to something like


Couldn't write to the database registration key


The user running the program has adminstrator rights and the program is run as administrator

How would I go around changing the permission in order to allow the script to be run when the machine starts or is there a better way to achieve the functionality I'm looking for?

Answer
                key = RegistryKey.OpenBaseKey(
                RegistryHive.LocalMachine, 
                RegistryView.Registry64
            ).OpenSubKey(subKey);

needs to be:

                key = RegistryKey.OpenBaseKey(
                RegistryHive.LocalMachine, 
                RegistryView.Registry64
            ).OpenSubKey(subKey, true);

to open for modify