C#开机自启动。

时间:2021-05-28 20:32:50
//----------------------------------------------------
        #region 2.开机自启动。         
        public static void SetAutoRun(string fileName, bool isAutoRun)
        {
            RegistryKey registryKey = null;
            try
            {
                if (!File.Exists(fileName))
                {
                    throw new Exception("该文件不存在!");
                }
                string name = fileName.Substring(fileName.LastIndexOf("\\") + 1);
                registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if (registryKey == null)
                {
                    registryKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                }
                if (isAutoRun)
                {
                    registryKey.SetValue(name, fileName);
                }
                else
                {
                    registryKey.SetValue(name, false);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                if (registryKey != null)
                {
                    registryKey.Close();
                }
            }
        }
        #endregion