Reputation: 1888
I have a tool which I want to run from my command prompt.
The code is as
static void Main(string[] args)
{
string User;
if (args[0].Length != 0)
{
User = args[0];
}
else
{
Console.Write("Please Enter the Username");
User = Console.ReadLine();
}
If I didnt give the username or the first argument after my 'tool.exe' in command prompt, it throws an exception like "Index was outside the bounds of the array"
I want ouptut as, if I didnt give argument - it should prompt me to give the username. please help me out.
Upvotes: 0
Views: 540
Reputation: 623
do this
static void Main(string[] args)
{
string User;
if (args.Length > 0)
{
User = args[0];
}
else
{
Console.Write("Please Enter the Username");
User = Console.ReadLine();
}
}
Upvotes: 1
Reputation: 3260
By doing like this you are looking on the first element in the collection string[].
if (args[0].Length != 0)
This will give a exception if there isn't any arguments. Correct statement are the following if you want to check if there is any arguments.
if (args.Length != 0)
//Or this
if (args.Any())
Observe that the Any() is a part of the namespace System.Linq.
Upvotes: 0
Reputation: 1221
You have to check length of argument array, i.e. the number of arguments. Currently you are checking the size of args[0].
if (args.Length != 0)
{
// command have some params
}
else
{
// command have no params
}
Upvotes: 0
Reputation: 758
Just replace the following line:
if (args[0].Length != 0)
With the following code:
if(arg.Length !=0) <br>
In your code, you have referenced item 0 in the args array and then check its length.
Since you want to check the array length, use the Length property of the array itselft
Upvotes: 0
Reputation: 2766
You need to change the if to:
static void Main(string[] args)
{
string User;
if (args.Length != 0) // Change from args[0] to args
{
User = args[0];
}
else
{
Console.Write("Please Enter the Username");
User = Console.ReadLine();
}
}
After this call make sure you do a
string.IsNullOrEmpty(User)
beforen you use it.
Upvotes: 1
Reputation: 15578
args
is an array, and is what you should be checking for length. When you check args[0].Length
you're actually assuming there's atleast one element in the array already and thus you're checking Length
of the first item.
Try
if (args.Length != 0)
instead, which checks the length of the array of command line parameters.
Upvotes: 3
Reputation: 191037
You don't want to call Length
on the item.
\/ Change here
if (args.Length != 0)
{
User = args[0];
}
else
{
Console.Write("Please Enter the Username");
User = Console.ReadLine();
}
Upvotes: 2