Shahroz Asif Shahroz Asif - 3 months ago 14
Vb.net Question

Prevent arg from showing MsgBox() if arg ends with ".lee" - VB.Net

I have program with

args
set as
Dim args As String() = Environment.GetCommandLineArgs()
. I used
arg
as
String
in
args
. The program checks if
arg
ends with
".lee"
then continues. Else if the
arg
ends with
".txt"
it still proceeds to next steps. Else if
arg
is not meeting the requirements, it should pop up a
MsgBox
.

What the problem is even if a supported type file is executed, my program seems to show the error dialog box.

Code:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim args As String() = Environment.GetCommandLineArgs()
For Each arg As String In args
If arg.EndsWith(".lee") Then
leeReader.RichTextBox1.LoadFile(arg, RichTextBoxStreamType.PlainText)
TextBox1.Text = leeReader.RichTextBox1.Text
Btn1.PerformClick()
Else
If arg.EndsWith(".txt") Then
leeReader.RichTextBox1.LoadFile(arg, RichTextBoxStreamType.PlainText)
TextBox1.Text = leeReader.RichTextBox1.Text
Btn1.PerformClick()
Else
MsgBox("We don't recommend unsupported files")
Me.Close()
End If
End If
Next
End Sub


I tried to add
Exit Sub
but it wouldn't work.

Code after changes:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim args As String() = Environment.GetCommandLineArgs()
For Each arg As String In args
If arg.EndsWith(".lee") Then
leeReader.RichTextBox1.LoadFile(arg, RichTextBoxStreamType.PlainText)
TextBox1.Text = leeReader.RichTextBox1.Text
Btn1.PerformClick()
Exit Sub
Else
If arg.EndsWith(".txt") Then
leeReader.RichTextBox1.LoadFile(arg, RichTextBoxStreamType.PlainText)
TextBox1.Text = leeReader.RichTextBox1.Text
Btn1.PerformClick()
Exit Sub
Else
MsgBox("We don't recommend unsupported files. Give it a try?")
End If
End If
Next
End Sub


If you know the solution/ If I am going wrong somewhere/ you need more help, please answer/ comment below.

Answer

You're looping through all the command line arguments, but (from the docs)

The first element is the executable file name, and the following zero or more elements contain the remaining command-line arguments.

So you're always going to see the messagebox for the first argument. Try: Environment.GetCommandLineArgs().Skip(1)

Comments