逃脱在C#中的命令行参数 [英] Escape command line arguments in c#

查看:190
本文介绍了逃脱在C#中的命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否足够来包装参数的引号和逃避 \

Is it enough to wrap the argument in quotes and escape \ and " ?

我要在命令行参数字串[] args 通过使用ProcessInfo.Arguments另一个进程。

I want to pass the command line arguments string[] args to another process using ProcessInfo.Arguments.

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);

问题是,我得到的参数作为数组,必须把它们合并成一个单一的字符串。一个论据可以制作欺骗我的程序。

The problem is that I get the arguments as an array and must merge them into a single string. An arguments could be crafted to trick my program.

my.exe "C:\Documents and Settings\MyPath \" --kill-all-humans \" except fry"

据<一href="http://stackoverflow.com/questions/653563/passing-command-line-arguments-in-c/653664#653664">this回答我创建了下面的函数来逃避一个参数,但我可能错过了一些东西。

According to this answer I have created the following function to escape a single argument, but I might have missed something.

private static string EscapeCommandLineArguments(string[] args)
{
    string arguments = "";
    foreach (string arg in args)
    {
        arguments += " \"" +
            arg.Replace ("\\", "\\\\").Replace("\"", "\\\"") +
            "\"";
    }
    return arguments;
}

这是不够好,或者是有任何框架功能呢?

Is this good enough or is there any framework function for this?

推荐答案

AFAIK没有框架的功能这一点。

AFAIK there is no framework function for this.

有关您简单的例子你在做什么看起来是足够的,除非程序到您所提交的参数recongnises任何字符作为特殊的以某种方式在这种情况下,你需要逃避那些为好。

For your simple use case what you are doing looks to be sufficient unless the program to which you are submitting the arguments recongnises any characters as being special in some way in which case you'd need to escape those as well.

这篇关于逃脱在C#中的命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆