C#代码从平面文件导入数据

时间:2016-09-08 14:11:23

标签: c# ssis-2012

当从第三方应用程序导入平面文件时,

sql server for sql server 2014会给出"列分隔符未找到错误"。

C#代码:

string[] source = Directory.GetFiles(@"\\share\data\", "*.txt");


using(SqlConnection conn = new SqlConnection("Data Source=sql_server;Initial Catalog=test;Integrated Security=SSPI"))
{
   string query = 
      "INSERT INTO dbo.srcText(uid, code, description) VALUES(@uid, @code, @description)";

   using(SqlCommand cmd = new SqlCommand(query, conn))
   {     
      cmd.Parameters.Add("@uid", SqlDbType.Int);
      cmd.Parameters.Add("@code", SqlDbType.VarChar, 10);
      cmd.Parameters.Add("@description", SqlDbType.VarChar, 500);


      foreach (string loadData in source)
      {

         string[] allrecords = File.ReadAllLines(loadData);

         conn.Open();


         for (int index = 1; index < allrecords.Length; index++)
         {
            // how would I include multiple text qualifiers
            string[] items = allrecords[index].Split(new char[] { '|' });

            cmd.Parameters["@uid"].Value = items[0];
            cmd.Parameters["@code"].Value = items[1];
            cmd.Parameters["@description"].Value = items[2];

            cmd.ExecuteNonQuery();
         }

         conn.Close();
      }
   }
}

如何通过处理多个文本限定符来使其更加健壮?

1 个答案:

答案 0 :(得分:1)

您可以创建一个拆分数组:

           char[] splits = new char[] { ',', '|', ';' };//add whatever delimiters you want here, surrounded by single quotes and separated by commas
        string[] parts;
        bool splitFound = false;//you could just test for parts==null but I'm adding this anyway. It allows handling a situation where no delimiters are found
        foreach(char splitter in splits)
        {
            parts = allrecords[index].Split(splitter);//this assumes that the text will never have any of the delimeters in it unless they are delimiting. If so, you need to handle first
            if (parts.Length > 0)
            {
                splitFound=true;
                break;
            }
        }
        if(splitFound){
        //process parts
             cmd.Parameters["@uid"].Value = parts[0];
            cmd.Parameters["@code"].Value = parts[1];
            cmd.Parameters["@description"].Value = parts[2];

            cmd.ExecuteNonQuery();

        }else{
            //handle no splits found
        }