Print all command line options

I am working on a console application that gets a pretty long list of options. For the purpose of debugging, I need to print the parameters passed to the output file. Right now, I am using the following code to execute command line options.

static void Main(string[] args)
{
    string Params = string.Empty;
    foreach(string arg in args)
    {
       Params += arg + ",";
    }
}

Is there a better way to do this?

+3
source share
7 answers

You can use this piece of code

String.Join(", ", Environment.GetCommandLineArgs())
+2
source

What about

Params = string.Join(",", args);

Your approach is foreachnot very effective. Since the string is immutable, this means that for each iteration of the loop, the string will be thrown out to collect garbage and a new string will be created. In case string.Joinonly one line is generated.

, , StringBuilder, string.Join, .

+5

String.Join( ",", args)

+1

, , , , , " " , .

: Foo.exe an example "is \"fine\", too" okay

: an, example, is "fine", too, okay. , .

, . , .

String.Join(", ", (from a in args select '"' + a.Replace("\"", @"\""") + '"'));

: "an", "example", "is \"fine\", too", "okay". , .

+1
String params = String.Join(",", args);
0

:

string.Join(",", args);

Strictly speaking, the Join function creates a StringBuilder with whole strings. Length * 16 (this is a 16 fixed number). If you have a different maximum args size, and if performance is critical to you, use a StringBuilder with a certain bandwidth.

0
source

It receives the exact command line arguments entered by the user;

string AppCMDName = Environment.GetCommandLineArgs()[0]; //get fully qualified application name with or without .exe specified  
//Environment.GetCommandLineArgs()[0] does not get surrounding double quotes used to qualify ...
//cmd line path that may contain spaces, single quotes not allowed
string commandLine = Environment.CommandLine.Replace(AppCMDName, "").TrimEnd();
if (commandLine.StartsWith("\"\""))
    commandLine = commandLine.Substring(2, commandLine.Length - 2).TrimStart(); 
    //remove surrounding quotes if used to specify cmd
0
source

Source: https://habr.com/ru/post/1789702/


All Articles