Heinzi
Heinzi

Reputation: 172230

Canonical solution for escaping .NET command line arguments

Question: Given a file name and an arbitrary list of strings, is there a canonical way to create a single command line such that Environment.GetCommandLineArgs (and C#'s void main(String[] args)/ VB's Sub Main(args() As String)) will return the same list of strings?


Background: The way .NET splits a command line into arguments is surprisingly complex, e.g.:

If a double quotation mark follows two or an even number of backslashes, each proceeding backslash pair is replaced with one backslash and the double quotation mark is removed. If a double quotation mark follows an odd number of backslashes, including just one, each preceding pair is replaced with one backslash and the remaining backslash is removed; however, in this case the double quotation mark is not removed.

Many try the simple "put every argument in double quotes and escape existing double quotes" approach and fail as soon as one of the arguments contains a trailing backslash. There have been various questions on StackOverflow regarding this issue, e.g.:

However, their answers are either not general enough to provide a canonical solution for all cases or appear to be developed "iteratively" ("Oh, there's one more special case I forgot, let's add it and now it should cover most cases..."). Since this is quite a common problem, I'd like to see a solution that provides confidence, for example, by either

Upvotes: 16

Views: 3411

Answers (3)

Anton Tykhyy
Anton Tykhyy

Reputation: 20066

This algorithm is generic and comes from a relatively authoritative source (MSDN blogs).

Upvotes: 3

Heinzi
Heinzi

Reputation: 172230

Starting with .NET Core 2.1, it's no longer necessary to escape command line arguments manually: ProcessStartInfo now has an ArgumentList property and automatically takes care of any escaping required.

To quote the example from the documentation:

var info = new System.Diagnostics.ProcessStartInfo("cmd.exe");
info.ArgumentList.Add("/c");
info.ArgumentList.Add("dir");
info.ArgumentList.Add(@"C:\Program Files\dotnet"); // there is no need to escape the space, the API takes care of it

Here you can see the algorithm in all its glory (including the famous "2n+1 backslash rule"). It's MIT licensed, which makes it easy to backport it to .NET Framework 4.8 projects, if requied.

Upvotes: 1

Panos Rontogiannis
Panos Rontogiannis

Reputation: 4172

A few years ago, Microsoft announced that they were going to release a command line parser on CodePlex (instead of the System.Shell.CommandLine that was supposed to ship with .NET Framework 4). I'm not sure if they actually did this. If you want a parser developed by a Microsoft employee have a look at cmdline. Also you can look for command line parses in CodePlex.

You could also try Mono.Options which is quite powerful.

Upvotes: 1

Related Questions