Escape command line arguments in c#

Short version:

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

Code version

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"

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?

72
задан Community 23 May 2017 в 11:54
поделиться