Hi rani,
Check this example. Now please take its reference and correct your code.
If you don't have header then change the loop condition.
Like in below article.
Namespaces
using System.Data;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
Controller
public class HomeController : Controller
{
private IHostingEnvironment Environment;
public HomeController(IHostingEnvironment _environment)
{
Environment = _environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(IFormFile postedFile)
{
if (postedFile != null)
{
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fileName = Path.GetFileName(postedFile.FileName);
string filePath = Path.Combine(path, fileName);
using (FileStream stream = new FileStream(filePath, FileMode.Create))
{
postedFile.CopyTo(stream);
}
string csvData = System.IO.File.ReadAllText(filePath);
DataTable dt = new DataTable();
bool firstRow = true;
foreach (string row in csvData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
if (!string.IsNullOrEmpty(row))
{
if (firstRow)
{
foreach (string cell in row.Split(','))
{
dt.Columns.Add(cell.Trim());
}
firstRow = false;
}
else
{
dt.Rows.Add();
int i = 0;
foreach (string cell in row.Split(','))
{
dt.Rows[dt.Rows.Count - 1][i] = cell.Trim();
i++;
}
}
}
}
}
return View(dt);
}
return View();
}
}
View
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using System.Data;
@model DataTable
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form asp-controller="Home" asp-action="Index" method="post" enctype="multipart/form-data">
<input type="file" name="postedFile" />
<input type="submit" value="Import" />
</form>
@if (Model != null)
{
<hr />
<table border="0" cellpadding="0" cellspacing="0">
<tr>
@foreach (DataColumn dc in Model.Columns)
{
<th>@dc.ColumnName</th>
}
</tr>
@foreach (DataRow dr in Model.Rows)
{
<tr>
@foreach (DataColumn dc in Model.Columns)
{
<td>@dr[dc.ColumnName]</td>
}
</tr>
}
</table>
}
</body>
</html>
Sample.csv
Id,Name,Country
1,John Hammond,United States
2,Mudassar Khan,India
3,Suzanne Mathews,France
4,Robert Schidner,Russia
Screenshot