将 SQL 服务器数据导出到 txt 文件时不要在最后一列后添加定界符 - c#

Not to add delimiter after last column while exporting SQL Server data to txt file - c#

我正在将 table 的数据从 SQL 服务器导出到文本文件。

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

我该如何预防?

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());
    }
}

改用string.Join

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

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

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

然后使用string.Join.

您需要修改这段代码:

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);
}
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);
          }
      }
 }