سؤال

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);
}
هل كانت مفيدة؟

المحلول

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);

نصائح أخرى

Use System.IO.Path.Combine for path concatenation. Also, make sure that the destination directory exists before copying.

string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string newpath = System.IO.Path.Combine(appData, "My_Application", "My_Application.exe");
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(newpath));
File.Copy(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString(), newpath);
RegistryKey startup = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
startup.SetValue("My_Application", newpath);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top