【C#】CSVファイルを作成する

■ 仕様

 * 文字コード「UTF8(BOMあり)」
 * 区切り文字「,」
 * データを「"」で囲う

■ サンプル

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
  public partial class Form1 : Form
  {

    private const string CsvDelimiter = ",";
    private const string CsvEncloser = "\"";

    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      var csvContents = new Dictionary<string, List<string>>()
      {
        { "Mike", new List<string> { "A1", "A2", "A3" } },
        { "Smith", new List<string> { "B1", "A2", "A3" } },
        { "Kevin", new List<string> { "C1", "C2", "C3" } },
        { "Kite", new List<string> { "D1", "D2", "D3" } },
        { "Tom", new List<string> { "E1", "E2", "E3" } },
      };

      createCsv(textBox1.Text, csvContents);
    }

    public void createCsv(string csvFilePath, Dictionary<string, List<string>> csvContents)
    {
      string csvContent = toCsvString(csvContents);
      createCsv(csvFilePath, csvContent);
    }

    public void createCsv(string csvFilePath, string csvContent)
    {
      File.WriteAllText(csvFilePath, csvContent, new UTF8Encoding(true));
    }

    public string toCsvString(Dictionary<string, List<string>> csvContents)
    {
      StringBuilder returnValue = new StringBuilder();
      foreach (var csvContent in csvContents)
      {
        returnValue.Append(CsvEncloser);
        returnValue.Append(csvContent.Key);
        returnValue.Append(CsvEncloser);
        foreach (var content in csvContent.Value)
        {
          returnValue.Append(CsvDelimiter);
          returnValue.Append(CsvEncloser);
          returnValue.Append(content);
          returnValue.Append(CsvEncloser);
        }
        returnValue.AppendLine();
      }
      return returnValue.ToString();
    }
  }
}

出力結果

"Mike","A1","A2","A3"
"Smith","B1","A2","A3"
"Kevin","C1","C2","C3"
"Kite","D1","D2","D3"
"Tom","E1","E2","E3"


関連記事

C#】ごっそりTextファイルにデータ入出力したい場合(ReadAllText()、WriteAllText())

https://blogs.yahoo.co.jp/dk521123/20151616.html