Search code examples
c#winformsvisual-studio-2010registry

Starting application on start-up, using the wrong path to load


I am using registry key to set my application to load on Windows Startup(after a user login). My Code:

RegistryKey RegKey = Registry.LocalMachine;
RegKey = RegKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
RegKey.SetValue("AppName", "\"" + @"C:\Users\Name\Desktop" + "\"");
RegKey.Close();

So with this code, my application load at startup, however the working directory is

C:\Windows\System32

Does anyone know why ?

This does not work for me because that program needs couple of files within the same directory as that one to operate. If the program loaded on my chosen directory("C:\Users\Name\Desktop") then the problem would not exist.

Anyone has any suggestion for this ?


Solution

  • Directory.SetCurrentDirectory() can be used to set your working directory when the app starts. EXE path can be retrieved using Application.ExecutablePath.

    Put them together:

    var fi = new FileInfo(Application.ExecutablePath);
    Directory.SetCurrentDirectory(fi.DirectoryName);