Skip to content

Suggestion: Include a CsvTextFileFormatter as well? #18

@osexpert

Description

@osexpert

This one from stackoverflow is good:

public static class CsvTextFileFormatter
{
	// https://stackoverflow.com/questions/6377454/escaping-tricky-string-to-csv-format
	public static string FormatCsvCell(char separator, string cell, bool alwaysQuote = false)
	{
		bool mustQuote(string cell) => cell.IndexOfAny(new char[] { separator, '"', '\r', '\n' }) > -1;

		if (alwaysQuote || mustQuote(cell))
		{
			StringBuilder sb = new StringBuilder();
			sb.Append('\"');
			foreach (char nextChar in cell)
			{
				sb.Append(nextChar);
				if (nextChar == '"')
					sb.Append('\"');
			}
			sb.Append('\"');
			return sb.ToString();
		}

		return cell;
	}

	public static string FormatCsvRow(char separator, IEnumerable<string> cells, bool alwaysQuote = false)
	{
		return string.Join(separator, values.Select(cell => FormatCsvCell(separator, cell, alwaysQuote)));
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions