the command
dotnet myapp.dll -- [4, 3, 2] throws the exception System.FormatException: Input string was not in a correct format.
I do not know the syntax. How should I pass arguments correctly?
I use powershell.
2 Answers
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(string.Join('-', args));
}
}
}
Call it via Powershell 6:
dotnet .\ConsoleApp3.dll "[1,2,3]"
Output:
[1,2,3]
In the above call, your Main method will receive [1,2,3] as a single string and you have to parse/split it in your code.
If you want an array reflected in the string[] array of Main you can use a PowerShell array:
dotnet .\ConsoleApp3.dll @(1,2,3)
Output:
1-2-3
Here the PowerShell array @(1,2,3) is casted to a string[]-array. Therefore each item of the PowerShell array is injected to the string[] array.
Behavior is the same on PowerShell 5.1.
2 Comments
dotnet .\myapp.dll @(4).Moerwald's answer explains well how to pass array arguments in PowerShell, but:
The regular arguments of a C# program (
string[] args) don't need to be sent as an array. Several parameters can be sent, just using spaces. As command line interpreters (PowerShell/CMD/BASH) just consider each of those different parameters, and will send all parameters to the dotnet command, and the dotnet command will send all those parameters to the program.Instead of:
> dotnet .\ConsoleApp3.dll @(1,2,3) 1-2-3You can send each argument separated by spaces:
> dotnet .\ConsoleApp3.dll 1 2 3 1-2-3You don't need to do compile the program into a DLL in order to run with dotnet.
Instead of first compiling the SLN/CSPROJ and then running it:
> dotnet build > cd bin\Debug\netcoreapp3.1 > dotnet .\ConsoleApp3.dll 1 2 3 1-2-3You can run directly from the SLN/CSPROJ folder via the "run" command:
> dotnet run 1 2 3 1-2-3
"[4, 3, 2]"[4, 3, 2]are three separate arguments:[4,,3,and2]. The quotes override this behavior by saying: everything between both quotes is one argument.System.String[]argsis an array of strings, it doesn’t overloadToString()so the output will be the type name.