C# - 如何在Windows系统中通过C#添加新的PATH条目至系统和用户环境变量

编写系统环境变量-->系统变量-->path-->添加新的列

01:直接写

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace updatesystempath01
{
    class Program
    {
        static void Main(string[] args)
        {
            const string targetPath = @"c:\aa"; // 目标路径

            try
            {
                // 获取当前系统的PATH环境变量
                string originalPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);

                // 检查PATH中是否已存在目标路径
                bool hasTargetPath = originalPath.Split(';')
                                                 .Any(path => path.Trim().ToLower() == targetPath.ToLower());

                if (!hasTargetPath)
                {
                    // 创建新PATH,将目标路径添加到原PATH后面
                    string newPath = originalPath + ";" + targetPath;
                    // 更新系统环境变量
                    using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true))
                    {
                        //key.SetValue("PATH", newPath, RegistryValueKind.ExpandString);

                        //Console.WriteLine("系统变量更新成功.");
                        if (key != null)
                        {
                            key.SetValue("PATH", newPath, RegistryValueKind.ExpandString);
                            Console.WriteLine("系统变量更新成功.");
                        }
                        else
                        {
                            Console.WriteLine("未能获取注册表键.");
                        }
                    }
                }
                else
                {
                    Console.WriteLine("系统变量已包含目标路径.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("系统变量更新出错: " + ex.Message);
            }

            // 执行完所有代码后立即退出程序
            Environment.Exit(0);
        }
    }
}

02:把新添加的内容添加进path.txt中,方便后面修改

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace updatesystempath01
{
    class Program
    {
        static void Main(string[] args)
        {
            // 尝试从文本文件读取目标路径
            string targetPathFromText;
            using (StreamReader reader = new StreamReader("path.txt"))
            {
                targetPathFromText = reader.ReadLine();
                if (string.IsNullOrEmpty(targetPathFromText))
                {
                    Console.WriteLine("文本文档为空或无法读取路径.");
                    return;
                }
            }

            try
            {
                string originalPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
                bool hasTargetPath = originalPath.Split(';')
                                                 .Any(path => path.Trim().ToLower() == targetPathFromText.ToLower());

                if (!hasTargetPath)
                {
                    string newPath = originalPath + ";" + targetPathFromText;
                    using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true))
                    {
                        if (key != null)
                        {
                            key.SetValue("PATH", newPath, RegistryValueKind.ExpandString);
                            Console.WriteLine("系统变量更新成功.");
                        }
                        else
                        {
                            Console.WriteLine("未能获取注册表键.");
                        }
                    }
                }
                else
                {
                    Console.WriteLine("系统变量已包含目标路径.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("系统变量更新出错: " + ex.Message);
            }

            // 程序结束
            Console.WriteLine("程序执行完毕。");
            // 执行完所有代码后立即退出程序
            Environment.Exit(0);
        }
    }
}
文本文档 (path.txt) 内容

确保path.txt文件位于你的项目目录中,并且内容为:

复制插入

c:\aa

编写系统环境变量-->用户变量-->path-->添加新的列
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace updatesystempath001
{
    class Program
    {
        static void Main(string[] args)
        {
            const string targetPath = @"c:\aa"; // 目标路径
            // 获取当前系统的PATH环境变量
            string originalPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);

            // 检查PATH中是否已存在"c:\aa"
            bool hasTargetPath = originalPath.Split(';')
                                              .Any(path => path.Trim().ToLower() == targetPath);

            if (!hasTargetPath)
            {
                // 创建新PATH,将"c:\aa"添加到原PATH后面
                // 创建新PATH,将目标路径添加到原PATH后面
                string newPath = originalPath + ";" + targetPath;
                // 更新系统环境变量
                try
                {
                    using (RegistryKey key = Registry.CurrentUser.OpenSubKey(
                        "Environment", true)) // 或者使用Registry.LocalMachine,取决于你要修改哪个用户的PATH
                    {
                        key.SetValue("PATH", newPath, RegistryValueKind.ExpandString);
                        
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error updating PATH: " + ex.Message);
                }
            }
            // 执行完所有代码后立即退出程序
            Environment.Exit(0);
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fyhs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值