I want to upload a text file and convert its data to datatable
this is my text file form:-
Code
Date/Time;MagazinePos;SampleID;SampleWeight;Moisture;Volatile;Ash;FixedCarbon;Standard;Customer
05-04-2023 15:34:08;1;rcs6737;1.410;3.283;23.761;41.395;31.561;-;HINDALCO
05-04-2023 15:34:08;2;rcs8434;1.100;3.938;26.521;35.089;34.452;-
05-04-2023 15:34:08;3;rcs6630;1.019;4.023;26.570;27.845;41.562;-
05-04-2023 15:34:08;4;rcs8960;1.022;4.266;26.563;33.735;35.436;-
Naimish MakwanaRank #324 · 7.7K reputationPosted Apr 12, 2023, 5:30 AM EDT
To write an API that can upload a text file and create a datatable in C#, you can follow these steps:
Here is a sample code that demonstrates the above steps:
[HttpPost] public IHttpActionResult UploadFile() { var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count < 1) { return BadRequest("No file uploaded."); } var file = httpRequest.Files[0]; var fileContent = new StreamReader(file.InputStream).ReadToEnd(); var dataTable = ConvertToDataTable(fileContent); return Ok(dataTable); } private DataTable ConvertToDataTable(string fileContent) { var lines = fileContent.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); var dataTable = new DataTable(); var headers = lines[0].Split(','); foreach (var header in headers) { dataTable.Columns.Add(header); } for (int i = 1; i < lines.Length; i++) { var values = lines[i].Split(','); var row = dataTable.NewRow(); for (int j = 0; j < headers.Length; j++) { row[j] = values[j]; } dataTable.Rows.Add(row); } return dataTable; }Thanks
Naimish Makwana
Jignesh KumarRank #91 · 22.9K reputationPosted Apr 12, 2023, 4:32 AM EDT
Hello,
You can create below controller and post method to upload file, and do call from UI using ajax,
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Data; using System.IO; using System.Threading.Tasks; namespace YourNamespace.Controllers { [ApiController] [Route("api/[controller]")] public class FileUploadController : ControllerBase { [HttpPost("upload")] public async Task UploadFile(IFormFile file) { if (file == null || file.Length == 0) { return BadRequest("Please select a file to upload"); } string fileContent; using (var reader = new StreamReader(file.OpenReadStream())) { fileContent = await reader.ReadToEndAsync(); } DataTable dataTable = new DataTable(); string[] lines = fileContent.Split("\n"); // create columns string[] headers = lines[0].Split(";"); foreach (string header in headers) { dataTable.Columns.Add(header.Trim()); } // add rows for (int i = 1; i < lines.Length; i++) { string[] values = lines[i].Split(";"); DataRow row = dataTable.NewRow(); for (int j = 0; j < headers.Length; j++) { row[j] = values[j].Trim(); } dataTable.Rows.Add(row); } return Ok(dataTable); } } }Sandeep KumarRank #1,642 · 937 reputationPosted Apr 12, 2023, 4:54 AM EDT
how can u do this via normal in c#