You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SSIS脚本任务实现:不发送仅含表头的空CSV文件至目标位置

解决方案:通过判断CSV行内容决定是否复制文件

完全可以通过读取CSV文件的行内容来准确判断是否仅含表头,避免文件大小判断的误差。核心逻辑是验证文件是否存在有效数据行,而非仅表头或表头加空行。

修改后的完整代码

public void Main()
{
    string sourceDir = Dts.Variables["SourceLocation"].Value.ToString();
    string destDir = Dts.Variables["DestinationLocation"].Value.ToString();
    string fileExt = Dts.Variables["CSVExtension"].Value.ToString();
    string[] csvFiles = Directory.GetFiles(sourceDir, fileExt);

    foreach (string sourcePath in csvFiles)
    {
        string fileName = Path.GetFileName(sourcePath);
        string destPath = Path.Combine(destDir, fileName);
        
        // 逐行读取优化(适合大文件,避免内存占用过高)
        bool hasValidData = false;
        using (StreamReader reader = new StreamReader(sourcePath, Encoding.UTF8))
        {
            // 跳过表头行
            reader.ReadLine();
            // 读取第二行,判断是否为有效数据行
            string secondLine = reader.ReadLine();
            hasValidData = secondLine != null && !string.IsNullOrWhiteSpace(secondLine);
        }
        
        if (hasValidData)
        {
            File.Copy(sourcePath, destPath, true);
        }
    }

    Dts.TaskResult = (int)ScriptResults.Success;
}

关键说明

  1. 修复原代码逻辑错误:原代码中s.Length是获取文件路径字符串的长度,并非文件内容大小,这是核心bug,现已替换为逐行读取的判断方式。
  2. 编码适配:StreamReader的编码参数可根据实际CSV文件编码调整(如GB2312、UTF-8带BOM等)。
  3. 判断逻辑:
    • 跳过第一行表头后,读取第二行
    • 若第二行不为空且非空白字符,则判定为含有效数据的文件,执行复制
  4. 性能优化:采用StreamReader逐行读取,避免一次性加载大文件到内存,适合处理大容量CSV。

可选简化方案(小文件场景)

如果CSV文件体积较小,也可以直接读取所有行进行判断:

string[] fileLines = File.ReadAllLines(sourcePath, Encoding.UTF8);
bool hasValidData = fileLines.Length > 1 && !string.IsNullOrWhiteSpace(fileLines[1]);

内容的提问来源于stack exchange,提问作者Junsh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 16:35:22