将数据表存储在平面文件中 - c#

这是我第一次对平面文件进行任何形式的工作。
我需要将其作为纯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);可以删除最后一个,,这是我能想到的唯一方法。
有什么建议?

参考方案

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

PHP str_replace是否具有大于13个字符的限制? - php

直到击中第13个字符为止。一旦str_ireplace在cyper数组中击中“ a”,str_ireplace就停止工作。数组的大小有限制吗?请记住,如果键入“ abgf”,我会得到“ nots”,但是如果键入“ abgrf”,我应该得到“ notes”,那么我就会得到“ notrs”。机架使我的大脑无法解决。$_cypher = array("n…

当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java

我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…

改造正在返回一个空的响应主体 - java

我正在尝试使用Retrofit和Gson解析一些JSON。但是,我得到的响应机构是空的。当我尝试从对象中打印信息时,出现NullPointerException。我确保URL正确,并且我也确保POJO也正确。我正在使用jsonschema2pojo来帮助创建POJO类。这是我要解析的JSON{ "?xml": { "@versi…

每个文件合并后添加换行 - python

我有很多类似以下内容的JSON文件:例如。1.json{"name": "one", "description": "testDescription...", "comment": ""} test.json{"name"…

Json到php,json_decode返回NULL - php

我正在用PHP进行JSON解析器的一些API,用于存储有关遗产的信息。我在解析时遇到问题,因为它返回的是NULL值而不是数组或对象。简单的JSON代码可以很好地解析,但是可以这样:{"success":true,"totalCount":1,"data":[{"id":99694…