I have tried unsuccessfully to enter from a CSV file to my data table. So far the code I have is the following:
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(IFormFile files)
{
var filePath = Path.GetTempFileName();
if (files.Length > 0)
{
var st = new MemoryStream();
await files.CopyToAsync(st);
//files.CopyTo(st);
var content = Encoding.UTF8.GetString(st.ToArray());
return Ok(content);
}
else
{
return Ok("ERROR");
}
}
Although it shows me the results with the return, I can not move forward to insert each record in my data table. Some help? Thank you very much already.
UPDATE
Although I was able to insert the records of the CSV file, it only does so from the second row. I tried leaving a single row and I see an exception that the format is not valid for the field to insert. (I clarify that this error does not appear when there is more than one record, insert well, but from the second row of my CSV file). I pass the code:
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(IFormFile files, Opj opj)
{
//long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
if (files.Length > 0)
{
var st = new MemoryStream();
await files.CopyToAsync(st);
//files.CopyTo(st);
var content = Encoding.UTF8.GetString(st.ToArray());
string[] datos = content.Split("\n");
foreach(var item in datos)
{
if(!string.IsNullOrEmpty(item))
{
var cells = item.Split(";");
opj.NroOrden = Convert.ToInt32(cells[0]);
opj.Abogado = cells[1];
opj.Caratula = cells[2];
opj.Dni = Convert.ToInt32(cells[3]);
opj.Importe = Convert.ToDecimal(cells[4]);
opj.Juzgado = Convert.ToInt32(cells[5]);
opj.Liquidada = false;
opj.NroExpediente = Convert.ToInt32(cells[6]);
opj.NroFolio = Convert.ToInt32(cells[7]);
opj.Presentacion = Convert.ToDateTime(cells[8]);
opj.RetencionGan = Convert.ToDecimal(cells[9]);
opj.RetencionIva = Convert.ToDecimal(cells[10]);
_context.Opjs.Add(opj);
}
}
_context.SaveChanges();
return Ok(content);
}
else
{
return Ok("ERROR");
}
}
UPDATE 2
@fredyfx Place a breakpoint to see how many lines it takes me. In my example file I only have 2 rows, but I am processing 512. Obviously I am doing something wrong. The question that arises is whether this is the best way. I add image of the breakpoint: