我正在将表的数据从 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());
}
}