private static RegistryKey _rlocal = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); /// <summary> /// 根據 app.config 中"isAuto",設置是否開機啟動 /// </summary> public static void AutoRun() { string appPath = System.Reflection.Assembly.GetExecutingAssembly().Location; //E:\Code\XXX.JobRunner\bin\Debug\KMHC.OCP.JobRunner.exe XXX是路徑和namespace var appName = appPath.Substring(appPath.LastIndexOf('\\') + 1); //XXX.JobRunner.exe XXX 是namespace try { var isAuto = ConfigurationManager.AppSettings["isAuto"]; if (isAuto == "1") { _rlocal.SetValue(appName, string.Format(@"""{0}""", appPath)); } else { _rlocal.DeleteValue(appName, false); } _rlocal.Close(); } catch (Exception ex) { Console.WriteLine(string.Format("設置開機是否啟動失敗: {0}", ex.Message)); } }
備注:需要開機啟動的程序最后設置為管理員權限