简体   繁体   中英

Output all command line parameters

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

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

Is there any better way to accomplish this?

What about

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

Your foreach approach is not very performant. Since a string is immutable , that means for each iteration of the loop, the string will get thrown away for garbage collection, and a new string will be generated. In the string.Join case, only one string will be generated.

Inside the loop, to get around the same performance, you will have to use a StringBuilder , but in this case it's really no reason not to use string.Join since the code will be much more readable.

你可以使用String.Join(“,”,args)

你可以使用这段代码

String.Join(", ", Environment.GetCommandLineArgs())

All of the answers here combining the arguments with a single comma will work, but I found that approach lacking somewhat because there's not a clear indicator of "quoted arguments" and those that might contain a comma.

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

The simple join suggestions will yield: an, example, is "fine", too, okay . Not bad, but not very clear and somewhat misleading.

Here's what I threw together that works well enough for me. I'm sure it could be improved further.

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

It returns the string: "an", "example", "is \\"fine\\", too", "okay" . I think this does a better job indicating the actual parameters.

String params = String.Join(",", args);

You should use:

string.Join(",", args);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM