There are lots of time which you want to get latest created file in a directory and do something with it, for example do a data transfer or do a file system task like delete or move.
As you may know the Foreach Loop Container in SSIS can loops through files of a directory, But it can not find latest file by creation date property.
So you need Scripting to achieve this. Fortunately SSIS have a powerful Script Task which give you Full power of .NET languages and you can do many things there.
this is the Script which returns Latest File full path in a User::LastFile variable ( code is in C# ):
public void Main()
{
string[] files = System.IO.Directory.GetFiles(@"C:\SSIS\Files");
System.IO.FileInfo finf;
DateTime lastDate = new DateTime();
string lastFile = string.Empty;
foreach (string f in files)
{
finf = new System.IO.FileInfo(f);
if (finf.CreationTime > lastDate)
{
lastDate = finf.CreationTime;
lastFile = f;
}
}
Dts.Variables["User::LastFile"].Value = lastFile;
Dts.TaskResult = (int)ScriptResults.Success;
}
As you see that was simple few lines of code that get result as you want. I hope SSIS Developers be familiar with .NET languages and use the power of Script Task each time they need.
There is another type of problems which Users need to find files in a directory which modified in few hours ago.
For example you want to loop through files of directory which modified in 24 hours ago, You can do this with this script :
public void Main()
{
string[] files = System.IO.Directory.GetFiles(@"C:\SSIS\Files");
DataTable NewList=new DataTable();
DataColumn col = new DataColumn("FileName");
NewList.Columns.Add(col);
System.IO.FileInfo finf;
foreach (string f in files)
{
finf = new System.IO.FileInfo(f);
if (finf.LastWriteTime > DateTime.Now.AddHours(-24))
{
NewList.Rows.Add(f);
}
}
Dts.Variables["User::FileNameArray"].Value = NewList;
Dts.TaskResult = (int)ScriptResults.Success;
}
Note that FileNameArray is an Object type variable, and after filling it in this script task, you can loop through it with Foreach loop container which enumerator configured as ado enumerator.
Hope these helps.