【问题标题】:Storing a DataTable in a Flatfile将数据表存储在平面文件中
【发布时间】:2012-06-09 09:49:19
【问题描述】:

这是我第一次对平面文件进行任何类型的工作。 我需要这是一个纯 txt 文件而不是 XML。

我写了以下选择逗号分隔的格式。

    public static void DataTableToFile(string fileLoc, DataTable dt)
    {
        StringBuilder str = new StringBuilder();
        // get the column headers
        foreach (DataColumn c in dt.Columns)
        {
            str.Append(c.ColumnName.ToString() + ",");
        }
        str.Remove(str.Length-1, 1);
        str.AppendLine();
        // write the data here
        foreach (DataRow dr in dt.Rows)
        {
            foreach (var field in dr.ItemArray)
            {
                str.Append(field.ToString() + ",");
            }
            str.Remove(str.Length-1, 1);
            str.AppendLine();
        }
        try
        {
            Write(fileLoc, str.ToString());
        }
        catch (Exception ex)
        {
            //ToDO:Add error logging
        }
    }

我的问题是:我可以做得更好或更快吗? str.Remove(str.Length-1, 1); 可以删除最后一个 ,,这是我能想到的唯一方法。 有什么建议吗?

【问题讨论】:

标签: c#


【解决方案1】:

使用

public static void DataTableToFile(string fileLoc, DataTable dt)
{
    StringBuilder str = new StringBuilder();

    // get the column headers
    str.Append(String.Join(",", dt.Columns.Cast<DataColumn>()
                                      .Select(col => col.ColumnName)) + "\r\n");

    // write the data here
    dt.Rows.Cast<DataRow>().ToList()
           .ForEach(row => str.Append(string.Join(",", row.ItemArray) + "\r\n"));

    try
    {
        Write(fileLoc, str.ToString());
    }
    catch (Exception ex)
    {
        //ToDO:Add error logging
    }
}

【讨论】:

  • 但这只会写入列名,而不是数据。
  • @Tim 我相信它是为了代表一种技术。您显然会逐行使用非常相似的东西。
  • @TimSchmelter:正是 MarcGarvll。他想要更快的代码而不是租用编码器。
【解决方案2】:

关键点是:没有必要在内存中用StringBuilder 构造它——你应该通过StreamWriter 之类的东西写入文件,即通过File.CreateText。 API 类似于StringBuilder,但您不应该尝试删除 - 相反,不要添加 - 即

bool first = true;
foreach(...blah...) {
    if(first) { first = false; }
    else { writer.Write(','); }
    ... write the data ...
}

另一个考虑因素:CSV 只是添加逗号的情况。您需要考虑引用文本(对于带有, 的数据)和多行数据。除非数据非常非常简单。您可能还希望使格式比.ToString() 更明确,后者对文化非常敏感。典型的例子是欧洲大部分地区使用, 作为十进制字符,因此“CSV”通常使用不同的分隔符,以避免必须引用所有内容。如果可以选择,个人我将始终使用 TSV 而不是 CSV - 问题较少(理论上,尽管您仍然需要处理带有标签的数据)。

【讨论】:

    猜你喜欢
    • 2018-02-21
    • 2010-09-12
    • 2012-09-22
    • 2012-08-20
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2013-10-24
    相关资源
    最近更新 更多