Lumito
Lumito

Reputation: 520

How to get command line arguments from position 1

Is there a way to get command line arguments in C# from args[1] and forward, excluding args[0]?

I've tried with this:

short argslenght = (short) args.Length;
string[] pargs = { "" };
for(int i = 1; i <= args.Length; i++)
{
    pargs[i-1] = args[i];
}

But gives me this error:

System.IndexOutOfRangeException

Thanks for your time.

Upvotes: 0

Views: 368

Answers (1)

Md. Suman Kabir
Md. Suman Kabir

Reputation: 5453

You are getting that error because you are trying to read a value from the array of index which exceeds the limit of the array length. It is happening for the last value. If there are 5 arguments, you can read the last one by args[4] but in your loop, you are trying to read it by args[5] which is causing the error.

You need to use Length -1 in your For loop, like this way:

for(int i = 1; i <= args.Length - 1; i++)

Or remove the = from the condition:

for(int i = 1; i < args.Length; i++)

Upvotes: 1

Related Questions