[英]Set ProcessStartInfo.EnvironmentVariables when Verb=“runas”
I am developing a C# application. 我正在开发一个C#应用程序。
I need to create and pass variables to a new process and I am doing it using ProcessStartInfo.EnvironmentVariables
. 我需要创建变量并将变量传递给新进程,我正在使用ProcessStartInfo.EnvironmentVariables
来完成它。
The new process must run elevated so I am using Verb = "runas" 新进程必须提升,所以我使用的是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());
}
The problem is that according to the msdn documentation : 问题是根据msdn文档 :
You must set the
UseShellExecute
property to false to start the process after changing theEnvironmentVariables
property. 必须将UseShellExecute
属性设置为false才能在更改EnvironmentVariables
属性后启动该进程。 IfUseShellExecute
is true, anInvalidOperationException
is thrown when the Start method is called. 如果UseShellExecute
为true,则在调用Start方法时抛出InvalidOperationException
。
but the runas
variable requires UseShellExecute=true 但runas
变量需要UseShellExecute = true
Is there a way to do both: run process as elevated and also set the environment variables? 有没有办法同时执行:将进程作为提升运行并设置环境变量?
EDIT 编辑
I will try to rephrase my question... 我会试着改写我的问题......
Is there a way to pass arguments securly to another process so only the other process will be able to read the arguments. 有没有办法将参数安全地传递给另一个进程,因此只有其他进程才能读取参数。
It works but on the downside is that it also shows a second command prompt, the enviroment vars are only set in the context of the started process so the settings are not propagating to the whole box. 它有效,但缺点是它还显示第二个命令提示符,环境变量仅在启动过程的上下文中设置,因此设置不会传播到整个框。
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);
}
有一个更好的答案:您仍然可以使用具有UseShellExecute = true的ProcessStartInfo调用Process.Start(),前提是您调用它的方法已使用[STAThread]属性标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.