0

The problem from https://stackoverflow.com/a/37859812/4878558

I need to set Registry value for current user, who launch the install up. Since install going for system mode - I don't know anything about current user

Also my code giving 'System.UnauthorizedAccessException'

SecurityIdentifier sID = WindowsIdentity.GetCurrent().User;
var subKey = Registry.Users.OpenSubKey(sID + "\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
subKey.SetValue("test", "test");
enter code here
Community
  • 1
  • 1
Curly Brace
  • 515
  • 3
  • 13

2 Answers2

1

As Ripple and I have both commented, there's no need for code. Go to the Registry view in the setup project, right-click on Software under HKEY_CURRENT_USER and add the key Microsoft, then Windows, the CurrentVersion, then Run, adding each key.

Then in the Run key view, right-click in the Name, View pane on the right and add new string value, the name being your name. The value, I assume, is the path to your exe, and (assuming it's in the Application folder) make the value [TARGETDIR]my.exe.

If your install is an "Everyone" install then there is a perfectly good reason why it cannot work. This is nothing to do with the code. In an Everyone install that custom action code is running with the System account (NOT the installing user) so you are trying to create a run key for the system account.

PhilDW
  • 20,260
  • 1
  • 18
  • 28
  • what if user want to add registry from a text/config file? I mean for every installation there will be different registry value. How to achieve that? @PhildDW – Harish Kumar Jun 01 '20 at 07:19
0

Here is how to write autostartup options:

const string AutorunRegistryKey = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run";
Registry.SetValue(AutorunRegistryKey, <AppName>, <PathToApplication>);

If you want to remove it from autostartup:

const string AutorunRelativePath = @"Software\Microsoft\Windows\CurrentVersion\Run\";
var key = Registry.CurrentUser.OpenSubKey(AutorunRelativePath, true);
    if (key != null)
    {
        key.DeleteValue(<AppName>, false);
        key.Close();
    }
vmg
  • 9,920
  • 13
  • 61
  • 90
  • The problem here, that I want to execute this via Setup Project, which generates msi installer. Setup will require admin access - Custom action will be executed from some SYSTEM/Admin account, not from initial user account. So, the program will not be started when initial user logs in. – Curly Brace Jun 16 '16 at 20:02
  • 1
    Why are you doing this with code? Just put it in the Registry view of the setup project. – PhilDW Jun 17 '16 at 17:06