简体   繁体   中英

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.

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++)

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