c# - 在动词 ="runas"时设置 ProcessStartInfo.EnvironmentVariables

标签 c# environment-variables processstartinfo runas

我正在开发 C# 应用程序。

我需要创建变量并将其传递给新进程,我正在使用 ProcessStartInfo.EnvironmentVariables 执行此操作。

新进程必须提升运行,所以我使用 Verb = "runas"

var startInfo =  new ProcessStartInfo(command)
{
    UseShellExecute = true,
    CreateNoWindow = true,
    Verb = "runas"
};
foreach (DictionaryEntry entry in enviromentVariables)
{
    startInfo.EnvironmentVariables.Add(entry.Key.ToString(), entry.Value.ToString());
}

问题是根据msdn documentation :

You must set the UseShellExecute property to false to start the process after changing the EnvironmentVariables property. If UseShellExecute is true, an InvalidOperationException is thrown when the Start method is called.

但是 runas 变量需要 UseShellExecute=true

有没有办法做到这两点:以提升的方式运行进程并设置环境变量?

编辑

我会尝试重新表述我的问题...

有没有办法将参数安全地传递给另一个进程,这样只有另一个进程才能读取参数。

最佳答案

它有效,但缺点是它还显示第二个命令提示符,环境变量仅在启动进程的上下文中设置,因此设置不会传播到整个框。

    static void Main(string[] args)
    {
        var command = "cmd.exe";
        var environmentVariables = new System.Collections.Hashtable();
        environmentVariables.Add("some", "value");
        environmentVariables.Add("someother", "value");

        var filename = Path.GetTempFileName() + ".cmd";
        StreamWriter sw = new StreamWriter(filename);
        sw.WriteLine("@echo off");
        foreach (DictionaryEntry entry in environmentVariables)
        {
            sw.WriteLine("set {0}={1}", entry.Key, entry.Value);
        } 
        sw.WriteLine("start /w {0}", command);
        sw.Close();
        var psi = new ProcessStartInfo(filename) {
            UseShellExecute = true, 
            Verb="runas"
        };
        var ps =  Process.Start(psi);
        ps.WaitForExit();
        File.Delete(filename);
    }

关于c# - 在动词 ="runas"时设置 ProcessStartInfo.EnvironmentVariables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11827486/

相关文章:

c# - "Item has already been added. Key in dictionary"的解决方法每次都使用相同的 key 但具有不同的值

c# - WPF 翻译转换

c# - Windows 服务,无法从我的安装程序的构造函数中访问 app.config

docker - 传递给 docker run 的环境变量

c# - 使用 System.Reflection 打印所有 System.Environment 信息

c# - 提升权限不适用于 UseShellExecute=false

c# - Asp.net 核心中的 SyndicationFeed

c# - 字符串字符串名称{get;设置;} vs stringName stringName {get;放;}

服务 env_file 的 Docker-compose 错误

c# - 尝试在命令提示符下运行相同的命令不起作用