我正在开发一个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
@H_404_32@UseShellExecute
property to false to start the process after changing theEnvironmentvariables
property. IfUseShellExecute
is true,anInvalidOperationException
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); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。