在Windows启动时启动wpf应用程序

Nea*_*eal 6 .net c# windows wpf

我开发了一个WPF应用程序,现在我必须在Windows启动时启动该应用程序.
为此,我写了下面的代码.我从这个答案得到了解决方案.
它在注册表中添加密钥但不启动应用程序.

Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
string str = Assembly.GetExecutingAssembly().Location;
key.SetValue("Camaleone", str);
Run Code Online (Sandbox Code Playgroud)

Smi*_*art 6

通过双击正常启动应用程序时,工作目录通常是exe文件的路径。这意味着,如果您在代码中引用任何设置文件,则可以找到它们。

但是,当您将其添加到注册表中以在启动时运行时,工作目录是c:\windows\system32因为它由Windows本身启动。

我通常使用这个:

public static string BaseDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Run Code Online (Sandbox Code Playgroud)

这意味着BaseDir现在是exe的路径。

每当我引用任何文件(例如设置文件)时,我都会使用:

string mySettingsFile = Path.Combine(BaseDir, "MySettingsFile.xml");
Run Code Online (Sandbox Code Playgroud)

  • 请小心使用Environment.CurrentDirectory,它返回工作目录,因此您最终可能会遇到同样的情况。 (2认同)