Skip to content

Instantly share code, notes, and snippets.

@ncelico
Created February 24, 2015 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ncelico/4a35497bb24c2b22e48d to your computer and use it in GitHub Desktop.
Save ncelico/4a35497bb24c2b22e48d to your computer and use it in GitHub Desktop.
SanitizeForCSV
private static string SanitizeForCSV(string s)
{
const string QUOTE = "\"";
const string ESCAPED_QUOTE = "\"\"";
char[] CHARACTERS_THAT_MUST_BE_QUOTED = { ',', '"', '\n' };
if (s == null)
return string.Empty;
if (s.Contains(QUOTE))
s = s.Replace(QUOTE, ESCAPED_QUOTE);
if (s.IndexOfAny(CHARACTERS_THAT_MUST_BE_QUOTED) > -1)
s = QUOTE + s + QUOTE;
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment