CommandLineBuilder Class
Provides methods for properly escaping and quoting command-line arguments for Windows applications.
public static class CommandLineBuilderRemarks
The implementation is based on the article: Everyone quotes command line arguments the wrong way.
Example
// Quote a single argument for standard Windows applications
var arg = CommandLineBuilder.WindowsQuotedArgument(@"path with spaces\file.txt");
Assert.Equal(@"""path with spaces\file.txt""", arg);
// Quote multiple arguments
var args = CommandLineBuilder.WindowsQuotedArguments("arg1", "path with spaces", "normal");
Assert.Equal(@"arg1 ""path with spaces"" normal", args);
// Quote for cmd.exe (escapes special characters like &, |, ^, etc.)
var cmdArg = CommandLineBuilder.WindowsCmdArgument(@"malicious argument"" & whoami");
Assert.Equal(@"^""malicious argument\^"" ^& whoami^""", cmdArg);Methods
| Name | Description |
|---|---|
| WindowsCmdArgument(string?) | Quotes and escapes a command-line argument for cmd.exe, handling special characters like (, ), %, !, ^, ", <, >, &, and |. |
| WindowsCmdArguments(string[]) | Quotes and escapes multiple command-line arguments for cmd.exe and joins them with spaces. |
| WindowsQuotedArgument(string?) | Quotes and escapes a command-line argument for standard Windows applications. |
| WindowsQuotedArguments(string[]) | Quotes and escapes multiple command-line arguments for standard Windows applications and joins them with spaces. |
WindowsCmdArgument(string?)
CommandLineBuilder.csQuotes and escapes a command-line argument for cmd.exe, handling special characters like (, ), %, !, ^, ", <, >, &, and |.
WindowsCmdArguments(string[])
CommandLineBuilder.csQuotes and escapes multiple command-line arguments for cmd.exe and joins them with spaces.
Parameters
valuesstring[]- The argument values to quote and escape.
Returns
string A string containing all quoted and escaped arguments joined with spaces, safe for cmd.exe execution.
WindowsQuotedArgument(string?)
CommandLineBuilder.csWindowsQuotedArguments(string[])
CommandLineBuilder.csQuotes and escapes multiple command-line arguments for standard Windows applications and joins them with spaces.
Parameters
valuesstring[]- The argument values to quote and escape.
Returns
string A string containing all quoted and escaped arguments joined with spaces.