我有一个平面文件源,每天必须将其加载到表中。我收到以下格式的文件“ filename_20190509040235.txt”
我使用表达式获取带有日期的文件名,如何获取时间戳?
每个日期的时间戳都不同。该文件在下午生成,并且该软件包计划每天晚上运行。
答案 0 :(得分:2)
假设您要基于文件名上的时间戳定义的某个特定时间加载文件,以下是此过程的概述。如前所述,将返回在执行包之前的12小时内带有时间戳的文件,您可能需要根据具体需要进行调整。这也使用您问题中指出的相同文件名/时间戳格式,即filename_20190509040235.txt。
在SSIS中创建对象和字符串变量。在平面文件连接管理器上,将字符串变量添加为连接字符串的表达式。可以在连接管理器上的“属性”窗口(按F4
)中进行操作,转到Expressions
字段,按其旁边的省略号,然后在下一个窗口中选择ConnectionString
属性并选择最近创建的字符串变量作为其表达式。
在控制流上添加脚本任务。在ReadWriteVariables
字段中添加对象变量。如果保存文件的目录存储在SSIS变量中,则在ReadOnlyVariables
字段中将该变量添加到。
下面的示例代码。您的帖子说文件是在下午生成的,文件包每晚运行。不确定确切的要求,只会返回当前时间后12个小时内带有时间戳的文件。您可以通过调整参数DateTime.Now.AddHours
来更改此参数,该参数当前会从当前时间中减去12小时(即加-12)。这将进入脚本任务的Main
方法中。确保也添加下面提到的参考。
在脚本任务之后添加一个Foreach循环,对于枚举器类型,选择Foreach From Variable Enumerator。在“收集”选项卡的“变量”字段上,选择在“脚本任务”中填充的对象变量。接下来,在“变量映射”窗格上,选择索引0处先前创建的字符串变量(设置为Flat File连接管理器的连接字符串)。
在Foreach循环内添加数据流任务。在数据流任务中,使用平面文件连接管理器创建平面文件源组件,然后添加适当的目标组件。将这两个连接起来,并确保将列正确映射到目标上。
脚本任务:
using System.IO;
using System.Collections.Generic;
//get source folder from SSIS string variable (if held there)
string sourceDirectory = Dts.Variables["User::SourceDirectory"].Value.ToString();
DirectoryInfo di = new DirectoryInfo(sourceDirectory);
List<string> recentFiles = new List<string>();
foreach (FileInfo fi in di.EnumerateFiles())
{
//use Name to only get file name, not path
string fileName = fi.Name;
string hour = fileName.Substring(17, 2);
string minute = fileName.Substring(19, 2);
string second = fileName.Substring(21, 2);
string year = fileName.Substring(9, 4);
string month = fileName.Substring(13, 2);
string day = fileName.Substring(15, 2);
string dateOnFile = month + "/" + day + "/" + year + " "
+ hour + ":" + minute + ":" + second;
DateTime fileDate;
//prevent errors in case of bad dates
if (DateTime.TryParse(dateOnFile, out fileDate))
{
//files from last 12 hours
if (fileDate >= DateTime.Now.AddHours(-12))
{
//FullName for file path
recentFiles.Add(fi.FullName);
}
}
}
//populate SSIS object variable with file list
Dts.Variables["User::ObjectVariable"].Value = recentFiles;