我正在开发一个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:
在更改
UseShellExecute
属性后,您必须将EnvironmentVariables
属性设置为false 以启动该过程。如果UseShellExecute
为真,则在调用Start方法时会抛出InvalidOperationException
。
但runas
变量需要 UseShellExecute = true
有没有办法同时执行这两种操作:将进程作为提升运行并设置环境变量?
修改
我会试着改写我的问题...
是否有办法将参数安全地传递给另一个进程,因此只有其他进程才能读取参数。
答案 0 :(得分:1)
它有效,但缺点是它还显示第二个命令提示符,环境变量仅在启动过程的上下文中设置,因此设置不会传播到整个框。
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);
}
答案 1 :(得分:0)
有一个更好的答案:您仍然可以使用具有UseShellExecute = true的ProcessStartInfo调用Process.Start(),前提是您调用它的方法已使用[STAThread]属性标记。