[英]How to safely append to ProcessStartInfo.EnvironmentVariables["PATH"]
[英]Set ProcessStartInfo.EnvironmentVariables when Verb=“runas”
我正在开发一个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文档 :
必须将
UseShellExecute
属性设置为false才能在更改EnvironmentVariables
属性后启动该进程。 如果UseShellExecute
为true,则在调用Start方法时抛出InvalidOperationException
。
但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);
}
有一个更好的答案:您仍然可以使用具有UseShellExecute = true的ProcessStartInfo调用Process.Start(),前提是您调用它的方法已使用[STAThread]属性标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.