Table of Contents

About

These functions escape a string which can then be part of a CSV string.

Code

C#

///////////////////////////////////////////////////////////////////////////
//    Copyright (C) 2015 Wizardry and Steamworks - License: CC BY 2.0    //
///////////////////////////////////////////////////////////////////////////
/// <summary>
///     Escapes a string to be used in a comma-separated list of values.
/// </summary>
/// <param name="input">the string to escape</param>
/// <returns>the escaped string</returns>
public static string wasCSVEscape(string input)
{
    input = new string(
        input.ToCharArray()
            .SelectMany(o => !o.Equals('"') ? new[] {o} : new[] {'"', '"'}).ToArray());
    return input.ToCharArray().Any(o => o.Equals(' ') || o.Equals(',') || o.Equals('\r') || o.Equals('\n'))
        ? "\"" + input + "\""
        : input;
}