title: Escape command line arguments in c#
body: <h1>Short version:</h1>
  <p>Is it enough to wrap the argument in quotes and escape <code>\</code> and <code>&quot;</code> ?</p>
  <h1>Code version</h1>
  <p>I want to pass the command line arguments <code>string[] args</code> to another process using ProcessInfo.Arguments.</p>
  <pre><code>ProcessStartInfo info = new ProcessStartInfo();
  info.FileName = Application.ExecutablePath;
  info.UseShellExecute = true;
  info.Verb = &quot;runas&quot;; // Provides Run as Administrator
  info.Arguments = EscapeCommandLineArguments(args);
  Process.Start(info);
  </code></pre>
  <p>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.</p>
  <pre><code>my.exe &quot;C:\Documents and Settings\MyPath \&quot; --kill-all-humans \&quot; except fry&quot;
  </code></pre>
  <p>According to <a href="https://stackoverflow.com/questions/653563/passing-command-line-arguments-in-c/653664#653664">this answer</a> I have created the following function to escape a single argument, but I might have missed something.</p>
  <pre><code>private static string EscapeCommandLineArguments(string[] args)
  {
      string arguments = &quot;&quot;;
      foreach (string arg in args)
      {
          arguments += &quot; \&quot;&quot; +
              arg.Replace (&quot;\\&quot;, &quot;\\\\&quot;).Replace(&quot;\&quot;&quot;, &quot;\\\&quot;&quot;) +
              &quot;\&quot;&quot;;
      }
      return arguments;
  }
  </code></pre>
  <p>Is this good enough or is there any framework function for this?</p>