将SQL Server数据导出到txt文件时不要在最后一列之后添加分隔符 - c#

时间:2016-03-10 20:07:41

标签: c# sql-server delimiter filereader export-to-text

我正在将表的数据从SQL Server导出到文本文件。

我想在除最后一列(标题+数据)之外的每一列之后追加一个分隔符,但我写的代码也在最后一列之后添加了一个分隔符。

我该如何预防?

public static void export_to_txt()
{
    SqlDataReader reader;

    string query = "Select * from tablename";
    string connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string strDelimiter = "\t";
    string strFilePath = @"mypath";

    StringBuilder sb = new StringBuilder();

    using (SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();

        using (reader = new SqlCommand(query, conn).ExecuteReader())
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                sb.Append(reader.GetName(i));
                sb.Append(strDelimiter);
            }

            sb.Append(Environment.NewLine);

            if (reader.HasRows)
            {
                Object[] items = new Object[reader.FieldCount];

                while (reader.Read())
                {
                    reader.GetValues(items);

                    foreach (var item in items)
                    {
                        sb.Append(item.ToString());
                        sb.Append(strDelimiter);
                    }

                    sb.Append(Environment.NewLine);
                }
            }
        }

        conn.Close();
        File.WriteAllText(strFilePath, sb.ToString());
    }
}

3 个答案:

答案 0 :(得分:3)

改为使用string.Join

 sb.Append(string.Join(strDelimiter, items));

对于标题行,您可以将其读入列表或使用LINQ:

var headers = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i));

然后使用string.Join

答案 1 :(得分:1)

您需要修改此代码:

for (int i = 0; i < reader.FieldCount; i++)
{
    sb.Append(reader.GetName(i));
    sb.Append(strDelimiter);
}

for (int i = 0; i < reader.FieldCount; i++)
{
    sb.Append(reader.GetName(i));
    if (i == reader.FieldCount - 1)
        continue;
    sb.Append(strDelimiter);
}

答案 2 :(得分:1)

using (reader = new SqlCommand(query, conn).ExecuteReader())
{
     for (int i = 0; i < reader.FieldCount; i++)
     {
           sb.Append(reader.GetName(i));
           if( i < (reader.FieldCount -1)
               sb.Append(strDelimiter);
     }
     sb.Append(Environment.NewLine);
     if (reader.HasRows)
     {
          Object[] items = new Object[reader.FieldCount];

          while (reader.Read())
          {
                reader.GetValues(items);
                sb.Append(string.Join(strDelimiter,item.ToString()));
                sb.Append(Environment.NewLine);
          }
      }
 }