CommandLineBuilder Class

Provides methods for properly escaping and quoting command-line arguments for Windows applications.

public static class CommandLineBuilder

Remarks

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

NameDescription
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.cs

Quotes and escapes a command-line argument for cmd.exe, handling special characters like (, ), %, !, ^, ", <, >, &, and |.

public static string? WindowsCmdArgument(string? value)

Parameters

value string?
The argument value to quote and escape.

Returns

string? The quoted and escaped argument string safe for cmd.exe, or null if value is null.

WindowsCmdArguments(string[])

CommandLineBuilder.cs

Quotes and escapes multiple command-line arguments for cmd.exe and joins them with spaces.

public static string WindowsCmdArguments(params string[] values)

Parameters

values string[]
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.cs

Quotes and escapes a command-line argument for standard Windows applications.

public static string? WindowsQuotedArgument(string? value)

Parameters

value string?
The argument value to quote and escape.

Returns

string? The quoted and escaped argument string, or null if value is null.

WindowsQuotedArguments(string[])

CommandLineBuilder.cs

Quotes and escapes multiple command-line arguments for standard Windows applications and joins them with spaces.

public static string WindowsQuotedArguments(params string[] values)

Parameters

values string[]
The argument values to quote and escape.

Returns

string A string containing all quoted and escaped arguments joined with spaces.