微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在开发一个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.

@H_404_32@

但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);
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐