Reputation: 225
I have a winform app and I put arguments "1-2-c:\temp-test" into Command Line arguments text box under Debug tab of Project property. The code as follows to read.
String[] arguments = Environment.GetCommandLineArgs();
string exeFilename = arguments[0];
string temp = arguments[1]; // return the argument string value. e.g."1-2-c:\temp-test"
string[] args = temp.Split('-');
try
{
string first = "", second="", third="", fourth = "";
if (args != null && args.Count() > 0)
{
first = string.IsNullOrEmpty(args[0]) ? "1" : args[0];
second = string.IsNullOrEmpty(args[1]) ? "2" : args[1];
third = string.IsNullOrEmpty(args[2]) ? @"c:\temp\" : args[2];
fourth = string.IsNullOrEmpty(args[3]) ? "test" : args[3];
}
catch(Exception ex)
{
string argsTest = "";
if (!string.IsNullOrEmpty(args[0]))
argsTest = args[0];
if (!string.IsNullOrEmpty(args[1]))
argsTest = argsTest + " "+ args[1];
if (!string.IsNullOrEmpty(args[2]))
argsTest = argsTest + " " + args[2];
if (!string.IsNullOrEmpty(args[3]))
argsTest = argsTest + " " + args[3];
MessageBox.Show(argsTest + " \n Error: " + ex.ToString());
}
when I run application form visual studio, it works fine but when I go to bin\debug and double click .exe file, I am getting the IndexOutOfRangeException exception.
Another observation, If I execute this exe with arguments from command prompt, it works fine.
Exception raised when I double click my exe file.
I searched and spent time to resolve but did not get any solution. I am totally stuck. Any kind of hints/code/advice is appreciable.
Upvotes: 0
Views: 567
Reputation: 186718
You should check for args.Length
when you want address an item at specific index, not for string.IsNullOrEmpty(args[...])
:
...
String first = (args.Length > 0) ? args[0] : "1";
String second = (args.Length > 1) ? args[1] : "2";
String third = (args.Length > 2) ? args[2] : @"c:\temp\";
String fourth = (args.Length > 3) ? args[3] : "test";
...
Upvotes: 0
Reputation: 7913
Setting debug commands in visual studio will not "embed" them in the exe
file. It only means that visual studio will pass those arguments when launching the exe
for debug.
Double clicking on the exe will effectively pass no arguments, which means that this instruction:
string exeFilename = arguments[0];
will generate the exception you're seeing.
A quick solution would be to test for the number of arguments before proceding:
if(arguments.Lenght >= 4){
//...do stuff...
}
Upvotes: 0
Reputation: 6744
If you need to run from the executable you have to pass in the command line arguments. This can be done in one of two common ways:
On a separate note you should probably check that your arguments have been supplied. i.e.
if (arguments.Length >= 2)
Upvotes: 0
Reputation: 210
When you're opening it via the .exe file, you're not supplying it any arguments. Make sure you're using some method to provide arguments when opening the .exe (from command prompt, or hard coding something in to test).
Upvotes: 1