'C#脚本任务在加载.CSV文件之前删除四重引号“

问题描述 投票:2回答:1

我有一个相当基本的SSIS包,它将.csv文件加载到SQL表中。但是,当程序包尝试读取数据流任务中的.csv源时,我收到错误消息:“未找到列'X'的列分隔符。处理文件”file.csv“时数据发生错误'Y'行。“

在这种情况下,正在发生的事情是,有成千上万的行包含四重引号中的字符串,即“Jane”Jill“Doe”。但是,在UltraEdit中手动删除这些行中的引号有效,我试图自动化这些包。派生列不起作用,因为它是分隔符的问题。

事实证明我需要一个脚本任务来删除四重引号,然后包才能正确加载文件。下面的代码(我从各种来源拼凑而成)被SSIS接受为无错误但在执行时遇到DTS脚本任务运行时错误:

#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
#endregion

namespace ST_a881d570d1a6495e84824a72bd28f44f
 {
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
    public void Main()
    {
        // TODO: Add your code here
        var fileContents = System.IO.File.ReadAllText(@"C:\\File.csv");

        fileContents = fileContents.Replace("<body>", "<body onload='jsFx();' />");
        fileContents = fileContents.Replace("</body>", "</body>");

        System.IO.File.WriteAllText(@"C:\\File.csv", fileContents);

    }

    #region ScriptResults declaration
    /// <summary>
    /// This enum provides a convenient shorthand within the scope of this class for setting the
    /// result of the script.
    /// 
    /// This code was generated automatically.
    /// </summary>
    enum ScriptResults
    {
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    };
    #endregion

    }
}

我的替代脚本是:

{
string filepath = (string)Dts.Variables[@C:\\"File.csv"].Value;
var fileContents = System.IO.File.ReadAllText(filepath);
fileContents = fileContents.Replace("\"\"", "");

System.IO.File.WriteAllText(@C:\\"File.csv", fileContents);

}

我究竟做错了什么?

c# ssis etl flat-file script-task
1个回答
2
投票

下面的C#示例将搜索csv文件,删除双引号文本中包含的任何双引号,然后将修改后的内容写回文件。正则表达式返回任何双引号的匹配,该双引号不在字符串的开头或结尾,或者在它之前/之后没有逗号,并用空字符串替换双引号。您可能已经这样做了,但请确保包含文件路径的变量列在脚本任务的ReadOnlyVariables字段中。

using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;


string filePath = Dts.Variables["User::FilePath"].Value.ToString();

List<String> outputRecords = new List<String>();
if (File.Exists(filePath))
{
 using (StreamReader rdr = new StreamReader(filePath))
 {
  string line;
  while ((line = rdr.ReadLine()) != null)
  {
      if (line.Contains(","))
      {
          string[] split = line.Split(',');

       //replace double qoutes between text
       line = Regex.Replace(line, "(?<!(,|^))\"(?!($|,))", x => x.Value.Replace("\"", ""));

      }
      outputRecords.Add(line);
    }
 }

 using (StreamWriter sw = new StreamWriter(filePath, false))
 {
     //write filtered records back to file
     foreach (string s in outputRecords)
         sw.WriteLine(s);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.