Skip to content

Instantly share code, notes, and snippets.

@pmachapman
Created November 5, 2018 03:58
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 pmachapman/6b78d5bb6cf519afce0cc46bb30b67e0 to your computer and use it in GitHub Desktop.
Save pmachapman/6b78d5bb6cf519afce0cc46bb30b67e0 to your computer and use it in GitHub Desktop.
Encode a field for a CSV file
/// <summary>
/// StringUtilities class
/// </summary>
public static class StringUtilities
{
/// <summary>
/// Encodes a string for a CSV field.
/// </summary>
/// <param name="field">The field to encode.</param>
/// <param name="separator">The separator (defaults to a comma).</param>
/// <returns>
/// A string suitable to output to a CSV file.
/// </returns>
public static string EncodeCsvField(string field, char separator = ',')
{
// Set up the string builder
StringBuilder sb = new StringBuilder(field);
// Some fields with special characters must be embedded in double quotes
bool embedInQuotes = false;
// Embed in quotes to preserve leading/trailing whitespace
if (sb.Length > 0 && (sb[0] == ' ' || sb[0] == '\t' || sb[sb.Length - 1] == ' ' || sb[sb.Length - 1] == '\t'))
{
embedInQuotes = true;
}
// If we have not yet found a reason to embed in quotes
if (!embedInQuotes)
{
for (int i = 0; i < sb.Length; i++)
{
// Embed in quotes to preserve commas, line-breaks etc.
if (sb[i] == separator || sb[i] == '\r' || sb[i] == '\n' || sb[i] == '"')
{
embedInQuotes = true;
break;
}
}
}
// If the field itself has quotes, they must each be represented by a pair of consecutive quotes.
if (embedInQuotes)
{
sb.Replace("\"", "\"\"");
return "\"" + sb.ToString() + "\"";
}
else
{
return sb.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment