C# Basic/Simple CSV builder

Date: 2022-04-12
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace Domain.Helpers
{
    public class CsvBuilder
    {
        private readonly List<List<object>> Lines = new();

        public void AddLine(params object[] data) => Lines.Add(data.ToList());
        
        private static string SerializeCsvValue(object value)
        {
            var x = value;
            if (x is bool b) x = b ? 1 : 0;
            if (x is DateTime d) x = string.Join(" ", d.ToString("s").Split('T'));

            var strVal = Convert.ToString(x, CultureInfo.InvariantCulture);
            if (string.IsNullOrWhiteSpace(strVal)) return "";

            if (NumberHelper.IsNumeric(x) || x is DateTime || x is bool)
                return $"\"{strVal.Replace("\"", "\"\"")}\"";

            // use \t as excel conversion trick see: https://superuser.com/a/704291/543593
            return $"\"\t{strVal.Replace("\"", "\"\"")}\"";
        }

        public string Build(string separator = ";")
        {
            var sb = new StringBuilder();
            sb.Append('\uFEFF'); // UTF-8 BOM for excel to display UTF-8 characters
            foreach (var line in Lines)
                sb.AppendLine(string.Join(separator, line.Select(SerializeCsvValue)));
            return sb.ToString();
        }
    }
}

61240cookie-checkC# Basic/Simple CSV builder