埋め込まれたコンマを処理する最良の方法は、CSVファイルを適切に引用することです。
- カンマを含む列は引用符で囲む必要があります
- 引用符を含む引用符付きの列では、引用符をエスケープする必要があります
例:
ジョー・スミス、「ジョー・スミス・ジュニア」、「ジョー」「ザ・マン」「スミス・ジュニア」
私はこれを解決するのに役立つ拡張メソッドを書きました:
static public string CsvQuote(this string text)
{
if (text == null) return string.Empty;
bool containsQuote = false;
bool containsComma = false;
int len = text.Length;
for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
{
char ch = text[i];
if (ch == '"')
{
containsQuote = true;
}
else if (ch == ',' || char.IsControl(ch))
{
containsComma = true;
}
}
bool mustQuote = containsComma || containsQuote;
if (containsQuote)
{
text = text.Replace("\"", "\"\"");
}
// Quote the cell and replace embedded quotes with double-quote or just return as is
return mustQuote ? "\"" + text + "\"" : text;
}
利用方法:
logger.Write(myString.CsvQuote());
var csv = string.Join(",", listOfStrings.Select(CsvQuote))