Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write csv file to string? #128

Closed
NeilMeredith opened this issue Apr 2, 2013 · 4 comments
Closed

Write csv file to string? #128

NeilMeredith opened this issue Apr 2, 2013 · 4 comments

Comments

@NeilMeredith
Copy link

I would like to use the csvhelper to export a list of objects to a csv file in the browser. All I see in the documentation are ways to write directly to a file - can you return the csv file as a string for export?

I tried something like this, but the 'WriteRecords' method is closing the memory stream:

 using (var memStream = new MemoryStream())
            {
                using (var csv = new CsvWriter(new StreamWriter(memStream)))
                {
                    csv.WriteRecords(events);
                    return File(memStream, "text/csv", "Report123.csv");
                }
            }
@JoshClose
Copy link
Owner

Yes. That is what most of the unit tests do...

using( var stream = new MemoryStream() )
using( var reader = new StreamReader( stream ) )
using( var writer = new StreamWriter( stream ) )
using( var csv = new CsvWriter( writer ) )
{
    csv.WriteRecords( events );
    writer.Flush();
    stream.Position = 0;
    var text = reader.ReadToEnd();
}

Or something similar. I did this from memory so not sure if it'll compile. ;)

@NeilMeredith
Copy link
Author

Thanks Josh, that did it. This is a great library!

@JoshClose
Copy link
Owner

You're welcome.

@JoeDM09
Copy link

JoeDM09 commented Jan 30, 2020

Found this via google and the answer is a bit old so thought I'd give it an update for anyone else who finds this.

using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture, true))
{
	csv.WriteRecord(csvRow);
	csv.Flush();
	var newRecord = writer.ToString();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants