JoshClose / CsvHelper

Library to help reading and writing CSV files
http://joshclose.github.io/CsvHelper/
Other
4.76k stars 1.07k forks source link

Write to string helper methods #494

Closed NN--- closed 7 years ago

NN--- commented 8 years ago

There are no simple helper methods to write CSV into simple string.

I would to have something like:

using System;
using System.IO'

class CsvStringUtils
{
    public static string WriteCsvRecord<T>(T record)
    {
        if (record == null) throw new ArgumentNullException("record");

        using (var s = new StringWriter())
        using (var w = new CsvWriter(s))
        {
            w.WriteRecord(record);

            return RemoveNewLine(s.GetStringBuilder());
        }
    }

    public static string WriteCsvHeader(Type type)
    {
        if (type == null) throw new ArgumentNullException("type");

        using (var s = new StringWriter())
        using (var w = new CsvWriter(s))
        {
            w.WriteHeader(type);
            return RemoveNewLine(s.GetStringBuilder());
        }
    }

    public static string WriteCsvHeader<T>()
    {
        return WriteCsvHeader(typeof(T));
    }

    private static string RemoveNewLine(StringBuilder sb)
    {
        sb.Length -= Environment.NewLine.Length;
        return sb.ToString();
    }
}

Thanks

JoshClose commented 8 years ago

Can you be more specific to the problem you are having? CsvHelper does exactly what you're saying.

http://joshclose.github.io/CsvHelper/#writing

NN--- commented 8 years ago

WriteRecord and WriteHeader add new line character in the end which I don't want to be written.

JoshClose commented 8 years ago

The newline char is part of the CSV spec though. You want to be able to flush records to the writer without it appending a newline char? Do you want to always do this, or just for the header? I'm curious what the use case is here.

NN--- commented 8 years ago

Wow, Didn't know that it is part of spec.

JoshClose commented 8 years ago

It's very small and simple, but very pretty strict. The unfortunate part is no one seems to follow it. https://tools.ietf.org/html/rfc4180