Reputation: 191
This is from a newer C# guy,
I have been back and forth through different questions posed on here but I haven't found anything that answers directly to what I need to know.
I have a console application that I want to pass arguments to, through the command line. This is what I have so far and it's working for a single argument, now I got to add another but I can't seem to figure out where to start.
static void Main(string[] args)
{
if (args == null || args.Length== 0)
{
Console.WriteLine("that's not it");
help();
}
else
{
for (int i = 0; i < args.Length; i++)
{
backupfolder = args[i];
}
checks();
}
}
If I take everything out of my else statement how can I set what the args are and assign? Will the below work ?
static void Main(string[] args)
{
if (args == null || args.Length== 0)
{
Console.WriteLine("that's not it");
help();
}
else
{
string backupfolder = args[0];
string filetype = args[1];
checks();
}
}
Upvotes: 9
Views: 3332
Reputation: 82524
You need to check the length of the args
array before attempting to retrieve values from it:
static void Main(string[] args)
{
// There must be at least 2 command line arguments...
if (args == null || args.Length < 2)
{
Console.WriteLine("that's not it");
help();
}
else
{
string backupfolder = args[0];
string filetype = args[1];
checks();
}
}
Another option, if you want to allow passing only some of the expected arguments:
static void Main(string[] args)
{
// There must be at least 1 command line arguments.
if (args == null || args.Length < 1)
{
Console.WriteLine("that's not it");
help();
}
else
{
// You already know there is at least one argument here...
string backupfolder = args[0];
// Check if there is a second argument,
// provide a default value if it's missing
string filetype = (args.Length > 1) ? args[1] : "" ;
checks();
}
}
Upvotes: 7