1

I want my application auto open while I start my computer. I found the code from Internet.

My code is like this:

private static void AutoOpen()
{           
  string starupPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
  RegistryKey loca = Registry.LocalMachine;
  RegistryKey run = loca.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

  try
  {
      run.SetValue("start", starupPath);
      loca.Close();
  }
  catch (Exception ee)
  {
      throw new Exception("start error :" + ee.ToString());

  }
}

While this program goes to the line

RegistryKey run = loca.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

It gives me an exception like this:

{"Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run' is denied."}

How do I avoid this exception?

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
  • 2
    Run the application with elevated privileges or tie into UAC. – Mike Perrenoud May 15 '14 at 20:12
  • 1
    FYI: do not catch an exception and throw a new exception. The original callstack is lost. Just makes debugging harder. – Thomas Weller May 15 '14 at 20:19
  • Right-click your executable and from the context menu select 'Run as Administrator' – Gayot Fow May 15 '14 at 20:21
  • @MichaelPerrenoud How I run my app with elevated privileges? Thank you. – user3617708 May 15 '14 at 20:22
  • Here is some guidance, http://stackoverflow.com/questions/573086/how-to-elevate-privileges-only-when-required and http://stackoverflow.com/questions/5276674/how-to-force-a-wpf-application-to-run-in-administrator-mode – Mike Perrenoud May 15 '14 at 20:24
  • @GayotFow Thank you, it works. I have another question, could I debug with elevated privileges too? – user3617708 May 15 '14 at 20:24
  • Yes, its easiest to start VS in admin mode, then any debug sessions also start with elevated privlidges. – BradleyDotNET May 15 '14 at 20:34
  • @MichaelPerrenoud Thank you a lot, I could run my program, but if I restart my computer, the program will run automatically still with the exception. I already change my app.manifest from `asInvoker` to `requireAdministrator`. – user3617708 May 15 '14 at 21:32
  • @user3617708, this question is going in to Russian Doll mode. If you have other questions, consider using the "Ask Question" button... – Gayot Fow May 15 '14 at 22:33

0 Answers0