Add application to Windows start-up registry for Current user

mrw 201 Reputation points
2023-09-09T09:45:38.3566667+00:00

I know there are a lot of similar topics on SO about this and I have tried most of the solutions without success. I want to create a string value for the startup of application on Windows start in current user registry. So I have created a class for that purpose. While looking at output provided by code

        Debug.WriteLine(subKey + " -- " + applicationPath);
        foreach (string s in names)
        {
          Debug.WriteLine(" ->>> " + s);
        }

I can see my application has been added. However while trying to Refresh or open close or restart my computer, I do not see this string value in my Registry path. Why so and how to fix it? Does this code work for others?

My application is 64 bit. I have tried also to change code to Local Machine and with admin rights string value is created properly in Registry path for Local Machine. However I do not want to run my application with admin rights all the time this parameter needs to be changed from application settings. For that reason I would like to use Current user. Also I have tried to do it with SID GetCurrentUserSid() that got SID correctly, but was not able to create string value in proper path either.

Here is my current class:

   public class WindowsStartupManager : IWindowsStartupManager
    {
      private const string RegistryKeyPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
    
      public bool IsStartupEnabled()
      {
        string applicationName = GetApplicationName();
    
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RegistryKeyPath))
        {
          if (key != null)
          {
            return key.GetValue(applicationName) != null;
          }
          else
          {
            // Handle the case where the Registry key is not found
            return false; 
          }
        }
      }
    
      public void EnableStartup()
      {
        string applicationName = GetApplicationName();
        string applicationPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
        string currentUserSid = GetCurrentUserSid();
    
        using (RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, this.GetRegistryView()))
        {
          using (RegistryKey subKey = key.OpenSubKey(RegistryKeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl))
          {
            subKey.SetValue(applicationName, applicationPath, RegistryValueKind.String);
    
            string[] names = subKey.GetValueNames();
    
            Debug.WriteLine(subKey + " -- " + applicationPath);
    
            foreach (string s in names)
            {
              Debug.WriteLine(" ->>> " + s);
            }
    
            subKey.Dispose();
          }
        }
      }
    
      public void DisableStartup()
      {
        string applicationName = GetApplicationName();
        string applicationPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
        string currentUserSid = GetCurrentUserSid();
    
        try
        {
          RegistryKey myKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, this.GetRegistryView());
          {
            using (RegistryKey subKey = myKey.OpenSubKey(RegistryKeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl))
            {
              subKey.DeleteValue(applicationName, false);
    
              string[] names = subKey.GetValueNames();
    
              Debug.WriteLine(subKey);
    
              foreach (string s in names)
              {
                Debug.WriteLine(" - " + s);
              }
    
              subKey.Close();
            }
          }
        }
        catch (Exception ex)
        {
          // Handle or log the exception
          Console.WriteLine("Failed to disable startup: " + ex.Message);
        }
      }
    
      public string GetApplicationName()
      {
        Assembly assembly = Assembly.GetEntryAssembly();
        return assembly.GetName().Name;
      }
    
      public string GetApplicationPath()
      {
        Assembly assembly = Assembly.GetEntryAssembly();
        return Path.GetDirectoryName(assembly.Location);
      }
    
      private RegistryView GetRegistryView()
      {
        // Determine the registry view based on the application's target platform
        bool is64BitProcess = Environment.Is64BitProcess;
        return is64BitProcess ? RegistryView.Registry64 : RegistryView.Registry32;
      }
    
      private string GetCurrentUserSid()
      {
        try
        {
          // Get the current user's Windows identity
          WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
    
          if (windowsIdentity != null)
          {
            // Get the user's SID
            return windowsIdentity.User.Value;
          }
          else
          {
            // Handle the case where the Windows identity is not available
            return string.Empty; // or throw new Exception("Windows identity not available");
          }
        }
        catch (Exception ex)
        {
          // Handle or log any exceptions that may occur
          Console.WriteLine("Failed to retrieve current user's SID: " + ex.Message);
          return string.Empty; // or throw the exception if necessary
        }
      }
    }
Windows
Windows
A family of Microsoft operating systems that run across personal computers, tablets, laptops, phones, internet of things devices, self-contained mixed reality headsets, large collaboration screens, and other devices.
5,823 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,420 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 44,696 Reputation points
    2023-09-11T14:50:54.66+00:00

    Hello there,

    Open your registry and find the key:

    [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run]

    For each program you want to start automatically create a new string value using a descriptive name, and set the value of the string to the program executable.

    For example, to automatically start Notepad, add a new entry of:

    "Notepad"="c:\windows\notepad.exe".

    Hope this resolves your Query !!

    --If the reply is helpful, please Upvote and Accept it as an answer–


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.