วันจันทร์ที่ 27 กุมภาพันธ์ พ.ศ. 2560

Async-Await CSVHelper - CSVWriter

I want to write and send the CSV file over network stream (response to GET service). I familiar with CSVHelper, which provides function to read and write CSV file, I apply it to my project.

Unfortunately, the service throw me the some exceptions. I googled it and found this issue in JonhClose GitHub, John is the creator! He did not put this feature to avoid blocking task.

I try to apply CSVHelperAsync to my project. But it does not work for me.

Then,, why I write this blog??? I want to tel you that the best way to do is to generate the CSV yourself and attach it to the response Message.

[HttpGet]
[Route("DownloadCSV")]
public HttpResponseMessage GetCSVContentInfoByProduct(int productId)
{
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    MemoryStream stream = _business.GetCSV();
    response.Content = new StreamContent(stream);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    { FileName = "myCsv.csv" };
    return response;
}

public MemoryStream GetCSV()
{
    MemoryStream stream = new MemoryStream();
    string csv = <<your_csv_string>>;
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(csv);
    writer.Flush();
    stream.Position = 0;
    return stream;

}

Have fun :D

ไม่มีความคิดเห็น:

แสดงความคิดเห็น