Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetCommandLineArgs is not returning what I expected

Tags:

c#

I recently started studying C# through the book and I came to this example where I'm trying to print out arguments passed from the command prompt:

namespace SimpleCSharpApp
{
    class Program
    {
        static void Main()
        {
            string[] theArgs = Environment.GetCommandLineArgs();

            foreach(string arg in theArgs)
                Console.WriteLine("Arg: {0}", arg);
        }
    }
}

My command prompt input looks like this:

D:\...\SimpleCSharpApp\bin\Debug>SimpleCSharpApp.exe arg1 arg2

And the output looks like this:

Arg: SimpleCSharpApp.exe

Arg: arg1

Arg: arg2

What I supposed it would look like is:

Arg: arg1

Arg: arg2

My question is, why does it recognize my execution command as a member of string arguments? What am I supposed to change to get the output I expected?

I could just change foreach loop into for loop starting from the 2nd element like this:

namespace SimpleCSharpApp
{
    class Program
    {
        static void Main()
        {
            string[] theArgs = Environment.GetCommandLineArgs();

            for (int i = 1; i < theArgs.Length; i++)
            {
                Console.WriteLine("Arg: {0}", theArgs[i]);
            }
        }
    }
}

But this does not resolve my curiosity, can I somehow make it not to record executable file like an argument and print it out with foreach loop to get the output I expected?

Thanks in advance!

like image 731
msmolcic Avatar asked Dec 03 '22 20:12

msmolcic


1 Answers

It is documented behaviour

The first element in the array contains the file name of the executing program. If the file name is not available, the first element is equal to String.Empty. The remaining elements contain any additional tokens entered on the command line.

If you want to skip First argument use Skip extension method.

 foreach(string arg in theArgs.Skip(1))
            Console.WriteLine("Arg: {0}", arg);
like image 62
Selman Genç Avatar answered Dec 22 '22 15:12

Selman Genç