Hi rani,
Check this example. Now please take its reference and correct your code.
Namespaces
using System.Data;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
Controller
public class HomeController : Controller
{
private IHostingEnvironment Environment;
private IConfiguration Configuration;
public HomeController(IHostingEnvironment _environment, IConfiguration _configuration)
{
Environment = _environment;
Configuration = _configuration;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult CSV(List<IFormFile> postedFiles)
{
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
DataSet ds = new DataSet();
foreach (IFormFile postedFile in postedFiles)
{
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 isHeader = true;
foreach (string row in csvData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
if (isHeader)
{
foreach (string cell in row.Split(','))
{
dt.Columns.Add(cell);
}
}
else
{
dt.Rows.Add();
int i = 0;
foreach (string cell in row.Split(','))
{
dt.Rows[dt.Rows.Count - 1][i] = cell;
i++;
}
}
isHeader = false;
}
}
ds.Tables.Add(dt);
}
DataTable dtMerge = ds.Tables[0].Clone();
foreach (DataTable table in ds.Tables)
{
dtMerge.Merge(table);
}
string csv = string.Empty;
foreach (DataColumn column in dtMerge.Columns)
{
csv += column.ColumnName + ',';
}
csv = csv.Remove(csv.Length - 1, 1);
csv += "\n";
foreach (DataRow row in dtMerge.Rows)
{
foreach (DataColumn column in dtMerge.Columns)
{
csv += row[column.ColumnName].ToString() + ',';
}
csv = csv.Remove(csv.Length - 1, 1);
csv += "\n";
}
return File(Encoding.UTF8.GetBytes(csv), "text/csv", "Merge.csv");
}
}
View
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form asp-controller="Home" method="post" enctype="multipart/form-data">
<input type="file" name="postedFiles" multiple />
<input type="submit" value="Merge CSV" asp-action="CSV" />
</form>
</body>
</html>