GetCommandLineArgs triggers "Index was outside the bounds of the array" anomaly on VB.NET

66 Views Asked by At

I have a program written in vb.net that when I run from the debugger runs fine but when I run the .exe file I get a "Index was outside the bounds of the array" anomaly. classic "it was running fine before" situation.

enter image description here

I placed a bunch of logs within my code to try to catch where is that anomaly being trigger, rebuilt and ran the .exe and I found that it fails when it runs this command:

myIntVariable= CInt(Environment.GetCommandLineArgs()(1))
lblStationNum.Text = "Station " + myIntVariable.ToString()

My command line argument in the properties option is set to 1, but it seems that when I run the executable it is defaulting to 0.(my variable is used to assign the value to "estacion")

enter image description here

I've seen in different posts in the Microsoft developer community that this problem was fixed many updates ago so I am pretty confused, the station that displays this problem is running VS2019 v16.11.23. running .NET Framework 4.6.1

Any feedback is appreciated, let me know if you need more details, there are virtually none since this happened after returning from the weekend.

I tried hard coding the value, it causes a conflict since I need to run 6 separate instances of the app at the same time.

2

There are 2 best solutions below

2
saul rivera On BEST ANSWER

I found my answer here

I created a shortcut to my .exe, on right-click->properties->Shortcut I added my argument on the target

eg Target: "C:\MyAppsLocation\myFile.exe" 1

Double clicking the shortcut sends the argument and my executable now runs.

1
Joel Coehoorn On

In .Net, array indexes start with 0. This means (1) is the second argument, not the first. Since there is only the single 1 value in the arguments box, this is past the end of the arguments array, causing your error. You want this instead:

myIntVariable= CInt(Environment.GetCommandLineArgs()(0))

Also, you should update to at least 4.6.2, as 4.6.1 no longer receives security patches. The 4.8 series would be even better, and would likely not even require any code changes.