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

使用SSIS脚本任务(C#)连接Azure Blob容器,检查并删除指定文件

我帮你把需求对应的SSIS脚本任务代码补全并整理好了,直接拿去用就行,关键细节都标出来了:

SSIS脚本任务:Azure Blob容器文件检查与删除实现

前置准备

  • 先给你的SSIS脚本任务项目安装WindowsAzure.Storage NuGet包,不然那些Azure存储的核心类会报错
  • 在SSIS包里新建一个整型变量(比如命名为User::FileExistsFlag),用来存储文件状态标记(1代表文件存在且已删除,0代表不存在)

完整C#代码

#region Namespaces
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
#endregion

public void Main()
{
    bool taskSuccess = false;
    try
    {
        // 1. 配置Azure存储参数(建议通过SSIS变量传入,这里用示例值)
        string storageConnStr = "你的Azure存储账户连接字符串";
        string containerName = "目标容器名称";
        string targetFileName = "abc.csv";

        // 2. 初始化存储账户与Blob客户端
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnStr);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer targetContainer = blobClient.GetContainerReference(containerName);

        // 3. 定位目标文件并检查存在性
        CloudBlockBlob targetBlob = targetContainer.GetBlockBlobReference(targetFileName);
        if (await targetBlob.ExistsAsync())
        {
            // 4. 更新SSIS变量为1
            Dts.Variables["User::FileExistsFlag"].Value = 1;
            
            // 5. 删除目标文件
            await targetBlob.DeleteAsync();
            taskSuccess = true;
            Console.WriteLine("abc.csv已存在,已删除并更新变量");
        }
        else
        {
            Dts.Variables["User::FileExistsFlag"].Value = 0;
            taskSuccess = true;
            Console.WriteLine("abc.csv不存在");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"执行出错:{ex.Message}");
        taskSuccess = false;
    }

    // 设置脚本任务最终执行结果
    Dts.TaskResult = taskSuccess ? (int)ScriptResults.Success : (int)ScriptResults.Failure;
}

enum ScriptResults
{
    Success = 0,
    Failure = 1
}

关键细节提醒

  • 连接字符串安全优化:别直接把连接字符串写死在代码里,最好存在SSIS配置变量或者Azure密钥保管库中,通过Dts.Variables["User::StorageConnStr"].Value.ToString()来获取
  • 变量权限设置:在脚本任务的「ReadWriteVariables」里一定要添加User::FileExistsFlag,不然会报变量访问权限错误
  • 异步适配:Azure存储的方法大多是异步的,确保你的SSIS项目使用的.NET Framework版本支持异步(推荐4.7.2及以上)
  • 异常处理:代码里加了try-catch块,可以避免单个文件操作失败导致整个SSIS包中断,你可以根据实际需求调整异常日志或重试逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:31:21