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

后端 未结 2 1009
旧巷少年郎
旧巷少年郎 2021-01-06 02:42

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 = R         


        
相关标签:
2条回答
  • 2021-01-06 03:40

    I've figured out a cheap trick on how to accomplish this. When your application starts up, Read the registry again to get your application's start-up path(the one you intended). For example: Appl1 has a startup path of "C:\Users\Name\Desktop\App1.exe".

    Once you read the registry for that path, set that as current directory. Something like this:

            RegistryKey RegKey = Registry.LocalMachine;
            RegKey = RegKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", false);
            string Path = RegKey.GetValue("App1.exe").ToString();
            Path = Path.Replace(@"\App1.exe"", ""); // Now it's a valid directory.
            Directory.SetCurrentDirectory(Path);
    

    This worked for me but if anyone has a better method, I would love to hear them.

    0 讨论(0)
  • 2021-01-06 03:44

    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);
    
    0 讨论(0)
提交回复
热议问题