Search code examples
c#copystartup

Copying a file and adding it to startup


I'm creating an application where I'm copying the file to the user's appdata and then adding a registry key so that the file runs at startup. I get a URI exception while running it. Here's the fragment of the code that's giving me trouble..

RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\My_Application");
if (rk != null)
{
    //Do nothing as the program is already added to startup
}
else
{
    string newpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\My_Application\\" + "My_Application.exe";
    File.Copy(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString(), Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\My_Application\\" + "My_Application.exe");
    RegistryKey startup = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    startup.SetValue("My_Application", "\"" + newpath);
}

Solution

  • The problem is in your startup.SetValue(). You are escaping a " character and I think you want to escape a \:

    startup.SetValue("My_Application", "\\" + newpath);
    

    If you actually mean to escape a " then you probably need one on both sides:

    startup.Setvalue("My_Application", "\"" + newpath + "\"");
    

    Or Typically this should work (I'm not super familiar with this API)

    startup.SetValue("My_Application", newpath);