Muhammad
Muhammad

Reputation: 93

'If' statement with multiple conditions over multiple lines in VB.net

I am checking the existence of two files and after that setting a condition but I am getting an error message that the syntax is incorrect when I add the AND

If (System.IO.Directory.GetFiles(CStr(Dts.Variables("VNetworkFolderName").Value), "Z_Attendance.xls").Length > 0
and System.IO.Directory.GetFiles(CStr(Dts.Variables("VNetworkFolderName").Value), "Z_EP.xls").Length > 0) Then
  Dts.Variables("VCountAPAListFile").Value = True
Else
  Dts.Variables("VCountAPAListFile").Value = False
End If

But if I check just one file without using AND statement, it works fine.

Upvotes: 2

Views: 11031

Answers (4)

Chris Dunaway
Chris Dunaway

Reputation: 11216

Calling GetFiles twice is a bad idea. It will iterate through all the folders in the directory twice! You would be better off using File.Exists instead:

Dim folderName As String = CStr(Dts.Variables("VNetworkFolderName").Value
Dim filename1 = Path.Combine(folderName, "Z_Attendance.xls")
Dim filename2 = Path.Combine(folderName, "Z_EP.xls")

Dts.Variables("VCountAPAListFile").Value =  File.Exists(filename1) AndAlso File.Exists(filename2)

Upvotes: 0

DreamTeK
DreamTeK

Reputation: 34177

Add an underscore _ before the line terminates to indicate a line break.

If (System.IO.Directory.GetFiles(CStr(Dts.Variables("VNetworkFolderName").Value), "Z_Attendance.xls").Length > 0 _
And System.IO.Directory.GetFiles(CStr(Dts.Variables("VNetworkFolderName").Value), "Z_EP.xls").Length > 0) Then
  Dts.Variables("VCountAPAListFile").Value = True
Else
  Dts.Variables("VCountAPAListFile").Value = False
End If

Upvotes: 3

the_lotus
the_lotus

Reputation: 12748

Depending on the version, the "And" should be on the first line with a _ at the end.

If (System.IO.Directory.GetFiles(CStr(Dts.Variables("VNetworkFolderName").Value), "Z_Attendance.xls").Length > 0 And _
    System.IO.Directory.GetFiles(CStr(Dts.Variables("VNetworkFolderName").Value), "Z_EP.xls").Length > 0) Then
  Dts.Variables("VCountAPAListFile").Value = True
Else
  Dts.Variables("VCountAPAListFile").Value = False
End If

Upvotes: 1

Matt
Matt

Reputation: 547

You need to either put the line break after the 'And' or use a line continuation character (underscore). Also, it's usually better to use 'AndAlso' in modern VB.

If condition _
    AndAlso otherCondition Then
    DoThing()
Else
    DoOtherThing()
End If

Or

 If condition AndAlso 
    otherCondition Then
    DoThing()
Else
    DoOtherThing()
End If

Upvotes: 2

Related Questions