1

I am trying to create an endpoint that accepts a CSV file but the data stream doesn't return any records.

This is my view model:

public class BulkUploadViewModel
{
    [Required]
    public IFormFile JobCsv { get; set; }
    [Required]
    public string UserId { get; set; }
}

And this is my endpoint:

[Route("BulkUpload")]
[HttpPost]
public async Task<IActionResult> BulkUpload(BulkUploadViewModel bulkUpload)
{
    if(!ModelState.IsValid)
    {
        return BadRequest();
    }

    List<BulkUploadDataModel> bulkList = new List<BulkUploadDataModel>();

    using (var memoryStream = new MemoryStream())
    {
        await bulkUpload.JobCsv.CopyToAsync(memoryStream);
        TextReader textReader = new StreamReader(memoryStream);

        var csv = new CsvReader(textReader);

        csv.Configuration.HasHeaderRecord = true;

        bulkList = csv.GetRecords<BulkUploadDataModel>().ToList();
    }

    return Ok(bulkList.Count());
}

I have also tried reading the CSV line by line but Csv.Read() returns false. I am not sure how to debug this.

I am generating the post with postman:

In the debugger I can see the file name and length value are populated correctly in bulkUpload.JobCsv so I assume my error is in how I am accessing the stream.

What did I do wrong?

2 Answers 2

3

You are just missing memoryStream.Position = 0 after
await bulkUpload.JobCsv.CopyToAsync(memoryStream);.

like this:

await bulkUpload.JobCsv.CopyToAsync(memoryStream);
memoryStream.Position = 0;
TextReader textReader = new StreamReader(memoryStream);
Sign up to request clarification or add additional context in comments.

Comments

0

I have Asp.Net project, where I use Csv package and this code to read csv from a file:

using (var stream = bulkUpload.JobCsv.OpenReadStream())
{
    var csvLines = CsvReader.ReadFromStream(stream).ToList();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.