Short version:
用引号将参数括起来并转义\
和"
就足够了吗?
Code version
我想使用ProcessInfo将命令行参数string[] args
传递给另一个进程.论据.
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = Application.ExecutablePath;
info.UseShellExecute = true;
info.Verb = "runas"; // Provides Run as Administrator
info.Arguments = EscapeCommandLineArguments(args);
Process.Start(info);
问题是,我将参数作为数组获取,并且必须将它们合并为单个字符串.可以精心设计一个参数来欺骗我的程序.
my.exe "C:\Documents and Settings\MyPath \" --kill-all-humans \" except fry"
根据this answer,我创建了以下函数来逃避一个参数,但我可能错过了一些东西.
private static string EscapeCommandLineArguments(string[] args)
{
string arguments = "";
foreach (string arg in args)
{
arguments += " \"" +
arg.Replace ("\\", "\\\\").Replace("\"", "\\\"") +
"\"";
}
return arguments;
}
这是否足够好,或者是否有任何框架功能?