private string QuoteValue(object val)
{
// Nulls don't get anything, they should just appear as ",,"
if (val == null)
{
return "";
}
StringBuilder sb = new StringBuilder();
bool useQuotes = false;
switch (_connDesc.OutputQuoteLevel)
{
case CsvQuoteLevel.QuoteAlways:
useQuotes = true;
break;
case CsvQuoteLevel.QuoteStrings:
if (val is string)
{
useQuotes = true;
}
break;
case CsvQuoteLevel.QuoteBareMinimum:
// Only quote it if it is a string that will break the CSV format.
if (val is string)
{
string strVal = (string) val;
if (strVal.IndexOfAny(new char[] {',', '"', '\n'}) != -1)
{
useQuotes = true;
}
}
break;
default:
throw new Exception("Unknown quote level: " + _connDesc.OutputQuoteLevel);
}
if (useQuotes)
{
// open quote.
sb.Append('"');
if (val is string)
{
// replace any double quotes with double double quotes, that is how they
// are escaped in a CSV.
val = ((string)val).Replace("\"", "\"\"");
}
}
// The value itself.
sb.Append(val);
if (useQuotes)
{
// close quote.
sb.Append('"');
}
return sb.ToString();
}