Home > OS >  CSV export Function, what to do if string contains the character seperator?
CSV export Function, what to do if string contains the character seperator?

Time:10-21

i use a fuction to convert a Datatable to CSV and i use File.WriteAllText to save it to a file.

    private static string DataTableToCSV(DataTable dtable, char seperator)
    {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < dtable.Columns.Count; i  )
        {
            sb.Append(dtable.Columns[i]);
            if (i < dtable.Columns.Count - 1)
                sb.Append(seperator);
        }
        sb.AppendLine();
        foreach (DataRow dr in dtable.Rows)
        {
            for (int i = 0; i < dtable.Columns.Count; i  )
            {
                sb.Append(dr[i].ToString());
                if (i < dtable.Columns.Count - 1)
                {
                    sb.Append(seperator);
                }
            }
            sb.AppendLine();
        }
        return sb.ToString();
    }

well, the Code is working. My problem is, in CSV the seperator is ';'. Now, of course, errors occur when a string in the table contains a semicolon. Is there perhaps an elegant way to solve the problem?

CodePudding user response:

I wrote a little helper for formatting every line of my CSV.

private string FormatForCsv(string value) => value != null && value.Contains(';') ? value.Replace(value, "\""   value   "\"") : value;

So then you can implement using:

sb.Append(FormatForCsv(dr[i]?.ToString()));

Of course you can use the same for the headers too.

I also added a null check when converting dr[i] to a string, just to be on the safe side.

  • Related