Skip to content

Instantly share code, notes, and snippets.

@WebFreak001
Created May 26, 2020 08:43
Show Gist options
  • Save WebFreak001/3651b7fabaa30b52e10c6d12d0c8bdf7 to your computer and use it in GitHub Desktop.
Save WebFreak001/3651b7fabaa30b52e10c6d12d0c8bdf7 to your computer and use it in GitHub Desktop.
Escape shell parameters for calling with the Win32 "CommandLine" argument (Process.StartInfo.Arguments)
/// <summary>
/// Escapes any given string input so that it can be reversed into
/// exactly this string by the Win32 CommandLineToArgvW method. Does not
/// perform any operation on the param string if it doesn't contain
/// whitespace or quotes.
/// </summary>
/// <param name="param">
/// The parameter to escape which can simply be appended to a whitespace
/// separated process parameter string list. (plus whitespace to
/// separate)
/// </param>
/// <returns>An escaped shell parameter</returns>
/// <see>https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw</see>
/// <see>https://docs.microsoft.com/en-us/previous-versions/17w5ykft(v=vs.85)</see>
public static string EscapeShellParam(string param)
{
if (param.Length == 0)
return "\"\"";
// if no whitespace or quotes
if (!param.Any(a => a <= ' ' || a == '"'))
return param;
StringBuilder ret = new StringBuilder(param.Length + 2);
ret.Append('"');
int backslash = 0;
foreach (var c in param)
{
if (c == '"')
{
ret.Append('\\', backslash + 1);
ret.Append('"');
backslash = 0;
}
else
{
if (c == '\\')
backslash++;
else
backslash = 0;
ret.Append(c);
}
}
if (backslash > 0)
ret.Append('\\', backslash);
ret.Append('"');
return ret.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment