加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 当Verb =“runas”时设置ProcessStartInfo.EnvironmentVar

发布时间:2020-12-15 21:38:43 所属栏目:百科 来源:网络整理
导读:我正在开发一个C#应用程序. 我需要创建变量并将变量传递给新进程,我正在使用ProcessStartInfo.EnvironmentVariables来完成它. 新进程必须提升,所以我使用的是Verb =“runas” var startInfo = new ProcessStartInfo(command){ UseShellExecute = true,Create
我正在开发一个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);
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读