CsvTextFieldParser icon indicating copy to clipboard operation
CsvTextFieldParser copied to clipboard

Suggestion: Include a CsvTextFileFormatter as well?

Open osexpert opened this issue 3 years ago • 1 comments

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

osexpert avatar Dec 02 '22 08:12 osexpert

Thanks for the suggestion. Even though the Microsoft VisualBasic assembly doesn't have any kind of formatter to go with its parser, I do agree it would be a useful thing to provide.

I started a formatter in #19. I tried to make it very similar to the parser in terms of method names and properties, and also in the constructors (even though I don't really like the all of the stream-based constructors in the parser).

If you have any suggestions or comments on that implementation, feel free to mention them here or in that pull request. Otherwise I'll plan on adding it to a release in a little while.

22222 avatar Dec 04 '22 17:12 22222