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

C#移动N天前文件到指定文件夹时SSIS包调用报错如何解决

报错根因

你遇到的"Exception has been thrown by the target of the invocation."是SSIS脚本任务的上层包装异常,真实错误由以下几个问题触发:

  • 核心逻辑错误:File.Move方法参数传值错误,当前代码传入了源文件夹路径、目标文件夹路径,而File.Move仅支持单个文件的移动,要求传入源文件完整路径、目标文件完整路径,传入文件夹路径会直接抛出IO异常。
  • 类名语法错误:代码中定义类时写为public partial class Script Main,类名中间存在多余空格,不符合C#语法规范,会直接导致编译失败。
  • 命名空间缺失:代码中直接使用File类,但没有引入System.IO命名空间,也没有写全类名System.IO.File,会触发类型找不到的编译错误。
  • 潜在权限问题:SSIS执行账户(调试时为当前登录账户,调度运行时为SQL Server代理服务账户)没有\\A\B的读取权限、\\A\C的写入权限,也会触发运行时异常。
  • 潜在重名冲突:如果目标文件夹中已存在同名文件,未做处理的情况下File.Move会直接抛出异常。
解决方法
  1. 修正类名,去掉中间多余空格,改为SSIS默认生成的ScriptMain。
  2. 补全System.IO命名空间引用,或者所有IO相关类都写全命名空间前缀。
  3. 修正File.Move的传参,拼接目标路径下的文件名,确保是单个文件维度的移动。
  4. 新增异常捕获逻辑,将真实错误信息输出到SSIS日志,方便后续问题排查。
  5. 校验SSIS运行账户对两个共享目录的读写权限,确保权限充足。
  6. 可选优化:将归档天数、源路径、目标路径配置为SSIS变量,避免硬编码,同时新增重名文件处理逻辑(覆盖/重命名)。
修正后完整代码
using System;
using System.IO;
using Microsoft.SqlServer.Dts.Runtime;

public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
    string rootFolderPath = @"\\A\B";
    string destinationPath = @"\\A\C";
    // 可改为从SSIS变量读取:int archiveDays = (int)Dts.Variables["User::ArchiveDays"].Value;
    int archiveDays = 1;

    public void Main()
    {
        try
        {
            // 确保目标目录存在,不存在则创建
            if (!Directory.Exists(destinationPath))
            {
                Directory.CreateDirectory(destinationPath);
            }

            string[] files = Directory.GetFiles(rootFolderPath);

            foreach (string file in files)
            {
                if (File.Exists(file))
                {
                    // 也可根据需求改为GetLastWriteTime判断修改时间
                    if (File.GetCreationTime(file) < DateTime.Now.AddDays(-archiveDays))
                    {
                        string destFilePath = Path.Combine(destinationPath, Path.GetFileName(file));
                        // 重名处理:如果目标文件存在则删除,也可改为追加时间戳重命名
                        if (File.Exists(destFilePath))
                        {
                            File.Delete(destFilePath);
                        }
                        File.Move(file, destFilePath);
                    }
                }
            }
            Dts.TaskResult = (int)ScriptResults.Success;
        }
        catch (Exception ex)
        {
            // 将真实错误信息输出到SSIS日志
            Dts.Events.FireError(0, "归档脚本错误", ex.Message + "\r\n" + ex.StackTrace, string.Empty, 0);
            Dts.TaskResult = (int)ScriptResults.Failure;
        }
    }

    #region ScriptResults declaration
    enum ScriptResults
    {
        Success = DTSExecResult.Success,
        Failure = DTSExecResult.Failure
    };
    #endregion
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:54:04