Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: Include a CsvTextFileFormatter as well? #18

Open
osexpert opened this issue Dec 2, 2022 · 1 comment
Open

Suggestion: Include a CsvTextFileFormatter as well? #18

osexpert opened this issue Dec 2, 2022 · 1 comment

Comments

@osexpert
Copy link

osexpert commented Dec 2, 2022

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)));
	}
}
@22222
Copy link
Owner

22222 commented Dec 4, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants