【问题标题】:How to get file name dynamically with time stamp in SSIS如何在 SSIS 中动态获取带有时间戳的文件名
【发布时间】:2019-05-10 04:19:03
【问题描述】:

我有一个平面文件源,必须每天将其加载到表格中。我收到以下格式的文件“filename_20190509040235.txt”

我使用表达式获取文件名和日期,如何获取时间戳?

每个日期的时间戳都不同。文件在下午生成,包计划每天晚上运行。

【问题讨论】:

标签: ssis


【解决方案1】:

假设您要根据文件名上的时间戳定义的特定时间加载文件,下面是此过程的概述。如前所述,将返回具有在包执行前 12 小时内的时间戳的文件,您可能需要根据您的特定需求进行调整。这也使用与您的问题中所示相同的文件名/时间戳格式,即 filename_20190509040235.txt。

  • 在 SSIS 中创建对象和字符串变量。在平面文件连接管理器上,添加字符串变量作为连接字符串的表达式。这可以从连接管理器上的“属性”窗口(按F4)完成,转到Expressions 字段,按旁边的省略号,在下一个窗口中选择ConnectionString 属性并选择最近创建的字符串变量作为 this 的表达式。

  • 在控制流上添加脚本任务。在ReadWriteVariables 字段中添加对象变量。如果保存文件的目录存储在 SSIS 变量中,则将此变量添加到 ReadOnlyVariables 字段中。

  • 示例代码如下。你的帖子说文件是在下午生成的,包每晚运行。不确定确切的要求,这只是返回当前时间 12 小时内时间戳的文件。您可以通过调整DateTime.Now.AddHours 的参数来更改此设置,该参数当前从当前时间减去 12 小时(即添加 -12)。这将进入脚本任务的Main 方法。请务必添加下面提到的参考资料。

  • 在脚本任务之后添加一个 Foreach 循环,并为枚举器类型选择 Foreach From Variable Enumerator。在集合选项卡的变量字段中,选择在脚本任务中填充的对象变量。接下来在 Variable Mappings 窗格中选择之前在索引 0 处创建的字符串变量(设置为平面文件连接管理器的连接字符串)。

  • 在 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;

【讨论】:

  • @twon 没问题。如果我的回答对您有帮助,请随时将其标记为已接受。没有义务这样做,只是让将来可能查看此帖子的人更清楚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
相关资源
最近更新 更多