C#软件开机自启动
private void AutoStart(bool isAuto = true, bool showinfo = true) { try { if (isAuto == true) { RegistryKey R_local = Registry.CurrentUser;//RegistryKey R_local = Registry.CurrentUser; RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); R_run.SetValue("应用名称", Application.ExecutablePath); R_run.Close(); R_local.Close(); } else { RegistryKey R_local = Registry.CurrentUser;//RegistryKey R_local = Registry.CurrentUser; RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); R_run.DeleteValue("应用名称", false); R_run.Close(); R_local.Close(); } } // if (showinfo) // MessageBox.Show("您需要管理员权限修改", "提示"); // Console.WriteLine("您需要管理员权限修改"); catch (Exception ex) { String LogPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log"); if (!Directory.Exists(LogPath)) Directory.CreateDirectory(LogPath); if (!File.Exists(LogPath + "\\log.txt")) File.Create(LogPath + "\\log.txt").Close(); string fileName = LogPath + "\\log.txt"; string content = DateTime.Now.ToLocalTime() + " 0001_" + "您需要管理员权限修改" + "\n" + ex.StackTrace + "\r\n"; Logger(fileName, content); } }
开机自动启动后 Environment.CurrentDirectory 会发生了变更,当程序中使用相对路径进行处理时,就找不见相应的文件了,可以在初始化程序时运行如下来解决。
Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步