C# 注册程序自启动

先上核心代码

  public class AutoStartUPHelper
    {
        /// <summary>
        /// 开机自启动 
        /// </summary>
        /// <param name="ButtinPath">执行文件路径</param>
        public void RegisterAutoStartUP(string KeyName,string ButtinPath)//"FacePC客户端"
        {
               
                using (RegistryKey rk = Registry.LocalMachine)
                {
                    RegistryKey runKey = rk.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                    if (runKey == null)
                    {
                        runKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                    }

                try
                {
                    runKey.SetValue(KeyName, ButtinPath);
                    runKey.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    runKey.Close();
                }
               
                }
        }

        /// <summary>
        /// 删除开机自启动 
        /// </summary>
        /// <param name="ButtinPath">执行文件路径</param>
        public void CancelAutoStartUP(string KeyName)//
        {
            using (RegistryKey reg = Registry.LocalMachine)
            {
                RegistryKey runKey = reg.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (runKey == null)
                {
                    runKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                }
                try
                {
                    //string keyValue = destPath + exeName;
                    runKey.DeleteValue(KeyName, true);
                    runKey.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    runKey.Close();
                }
            }
        }
    }

代码很简单 但是我测试的时候老是注册失败 后来发现一个奇葩的问题:我测试时候使用的路径路径分隔符为“/” 这样注册出来虽然程序出现在了启动项 但是点击打开服务所在文件路径会没反应 ,尝试多次后改路径间隔符为“\” .然后终于成功了 mmp 看来操作注册表路径间隔符必须为“\”

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值