ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

CSVQuoted

If a string contains a space or a comma or a newline, quotes it, suitable for a field in a CSV file.

Source

public static string CSVQuoted( this string s )
{
    if ( s.IndexOfAny(" ,\n".ToCharArray()) < 0 && s.Trim() == s )
        return s;

    StringBuilder sb = new StringBuilder();
    sb.Append( '"' );
    foreach ( char c in s )
    {
        sb.Append(c);
        if ( c == '"' )
            sb.Append(c);
    }
    sb.Append( '"' );
    return sb.ToString();
}

Example

"this".CSVQuoted()  ==>  "this"
"pots and pans".CSVQuoted() ==> "\"pots and pans\""
"blue,red".CSVQuoted() ==> "\"blue,red\""
"embedded\"quote".CSVQuoted() ==> "\"embedded\"\"quote\""
" goodbye! ".CSVQuoted() ==> "\" goodbye! \""

Author: David Bakin

Submitted on: 8 mrt. 2009

Language: C#

Type: System.String

Views: 5270