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;

posted @ 2024-02-18 17:41  东经115  阅读(27)  评论(0编辑  收藏  举报