为了账号安全,请及时绑定邮箱和手机立即绑定

C#中的转义命令行参数

C#中的转义命令行参数

C#
慕尼黑8549860 2019-12-12 14:10:36
简洁版本:将参数用引号引起来并转义\和是否足够"?代码版本我想string[] args使用ProcessInfo.Arguments 将命令行参数传递给另一个进程。ProcessStartInfo info = new ProcessStartInfo();info.FileName = Application.ExecutablePath;info.UseShellExecute = true;info.Verb = "runas"; // Provides Run as Administratorinfo.Arguments = EscapeCommandLineArguments(args);Process.Start(info);问题是我将参数作为数组获取,必须将它们合并为单个字符串。可以设计一个参数来欺骗我的程序。my.exe "C:\Documents and Settings\MyPath \" --kill-all-humans \" except fry"根据这个答案,我创建了以下函数来转义单个参数,但是我可能错过了一些东西。private static string EscapeCommandLineArguments(string[] args){    string arguments = "";    foreach (string arg in args)    {        arguments += " \"" +            arg.Replace ("\\", "\\\\").Replace("\"", "\\\"") +            "\"";    }    return arguments;}这足够好还是有任何框架功能呢?
查看完整描述

3 回答

?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

我也遇到这个问题。我没有解析args,而是采用了完整的原始命令行并修剪了可执行文件。即使不需要/未使用,这也具有在呼叫中保留空格的额外好处。它仍然必须在可执行文件中追逐转义符,但这似乎比args容易。


var commandLine = Environment.CommandLine;

var argumentsString = "";


if(args.Length > 0)

{

    // Re-escaping args to be the exact same as they were passed is hard and misses whitespace.

    // Use the original command line and trim off the executable to get the args.

    var argIndex = -1;

    if(commandLine[0] == '"')

    {

        //Double-quotes mean we need to dig to find the closing double-quote.

        var backslashPending = false;

        var secondDoublequoteIndex = -1;

        for(var i = 1; i < commandLine.Length; i++)

        {

            if(backslashPending)

            {

                backslashPending = false;

                continue;

            }

            if(commandLine[i] == '\\')

            {

                backslashPending = true;

                continue;

            }

            if(commandLine[i] == '"')

            {

                secondDoublequoteIndex = i + 1;

                break;

            }

        }

        argIndex = secondDoublequoteIndex;

    }

    else

    {

        // No double-quotes, so args begin after first whitespace.

        argIndex = commandLine.IndexOf(" ", System.StringComparison.Ordinal);

    }

    if(argIndex != -1)

    {

        argumentsString = commandLine.Substring(argIndex + 1);

    }

}


Console.WriteLine("argumentsString: " + argumentsString);



查看完整回答
反对 回复 2019-12-14
  • 3 回答
  • 0 关注
  • 249 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信