c#环境变量值没有被添加

本文关键字:添加 变量值 环境 环境变量 | 更新日期: 2023-09-27 18:07:00

我正试图为Path环境变量添加一个值,但我似乎无法让它工作。我经历了几个类似的问题,我很确定我有完全相同的代码,但它仍然不会添加变量我看不见它。我已经检查了管理员和本地用户帐户的更改。我在应用程序运行(调试)期间和之后都进行了检查。我还完全关闭了VS2013并检查了。

下面是我使用的代码

string path = @"C:'Users'bono'Documents'Visual Studio 2013'Projects'3D-Scanner'AddEnviromentToPath'bin'Debug'AddEnviromentToPath.exe";
ProcessStartInfo process_start_info = new ProcessStartInfo();
process_start_info.FileName = path;
process_start_info.Verb = "runas";
process_start_info.WindowStyle = ProcessWindowStyle.Normal;
process_start_info.UseShellExecute = true;
process_start_info.Arguments = PATH_TO_PCL;
Process.Start(process_start_info); //Process that handles the adding of the value

AddEnviromentToPath程序:

class Program {
    static void Main(string[] args) {
        //Just to make sure we're adding both
        AddToEnvironmentPath(args[0], EnvironmentVariableTarget.User);
        AddToEnvironmentPath(args[0], EnvironmentVariableTarget.Machine);
    }
    static void AddToEnvironmentPath(string pathComponent, EnvironmentVariableTarget target) {
        string targetPath = System.Environment.GetEnvironmentVariable("Path", target) ?? string.Empty;
        if (!string.IsNullOrEmpty(targetPath) && !targetPath.EndsWith(";")) {
            targetPath = targetPath + ';';
        }
        targetPath = targetPath + pathComponent;
        Environment.SetEnvironmentVariable("Path", targetPath, target);
    }
}

请注意,我以标准用户身份运行VS2013和主应用程序。当AddEnviromentToPath程序运行时,我得到一个管理员验证面板。我是用管理员账号登录的。

编辑:

其他人似乎用基本相同的代码使它工作:
如何在c#中获取和设置环境变量?
没有在使用c#的windows中设置环境。我哪里做错了?

c#环境变量值没有被添加

假设Environment.SetEnvironmentVariable在幕后调用Win32 SetEnvironmentVariable函数,此说明可能适用:

设置指定环境变量的内容当前进程

…该功能对系统无影响环境变量或其他进程的环境变量

如果你想改变一个全局环境变量并让现有进程注意到它,你需要:

  • 保存到HKEY_LOCAL_MACHINE'SYSTEM'CurrentControlSet'Control'Session Manager'Environment下的注册表
  • WM_SETTINGCHANGE消息通知现有进程更改。

有关详细信息,请参阅MSDN环境变量文档

ProcessStartInfo来救援!

你需要查看这个文档:

https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.environmentvariables%28v=vs.110%29.aspx

解决您关注的关键文本:

虽然不能设置EnvironmentVariables属性,但是可以修改属性返回的StringDictionary