我正在开发 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 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);
}
关于c# - 在动词 ="runas"时设置 ProcessStartInfo.EnvironmentVariables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11827486/