我正在开发一个 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文档 http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.environmentvariables.aspx:
您必须设置UseShellExecute
属性为 false更改后启动该过程EnvironmentVariables
财产。如果UseShellExecute
是真的,一个InvalidOperationException
调用 Start 方法时抛出。
but the runas
变量要求UseShellExecute=true
有没有办法做到这两点:以提升的方式运行进程并设置环境变量?
EDIT
我会尝试重新表述我的问题......
有没有办法将参数安全地传递给另一个进程,以便只有另一个进程才能读取参数。
它可以工作,但缺点是它还显示第二个命令提示符,环境变量仅在启动进程的上下文中设置,因此设置不会传播到整个盒子。
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)