(Another way to handle this is to use the ForEach task and use a wildcard in there, but I am going to blog about that next week)
First, I add a variable to my package. I usually call this variable FileExists and set it as a Boolean, with a default value of False.
I then add a script task to my control flow. In the Read/Write variable property, I add User::FileExists.
In the script editor, I use this script:
Public Class ScriptMain
Public Sub Main()
Dim di As DirectoryInfo = New DirectoryInfo("c:\")
Dim fi As FileInfo() = di.GetFiles("*.txt")
If fi.Length > 0 Then
Dts.Variables("User::FileExists").Value = True
Dts.Variables("User::FileExists").Value = False
Dts.TaskResult = Dts.Results.Success
This searches c:\ for a file *.txt. The Length property of FileInfo is the number of files found. If this is greater than zero, I set the FileExists variable to True.
After closing the script editor, and clicking OK on the script task property window, I am ready to set up my precedence constraint.
I then add my next task to the control flow and drag the flow control from the script task to the new task. I right click on the constraint and select edit. I select Expression in the Evaluation Operation drop down box. For the expression I use: @[User::FileExists]==true. This way, the only way the next task is executed is if files exist. If the don’t exists, the package ends gracefully.
You could add another task to log the fact that there were no files, connect the script to that task, and set the expression to: @[User::FileExists]==false.