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.
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.
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();
}
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.
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();
}
}
You have to check length of argument array, ie 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
}
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
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.
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.