Merge (Combine) multiple text (.txt) files into one in ASP.Net Core MVC

Last Reply 8 days ago By dharmendr

Posted 9 days ago

What is the best way to combine multiple text files into one in core.

Posted 8 days ago

Hi rani,

Check this example. Now please take its reference and correct your code.


using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;


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();

    public IActionResult Text(List<IFormFile> postedFiles)
        string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
        if (!Directory.Exists(path))
        List<string> files = new List<string>();
        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))

        using (StreamWriter writer = new StreamWriter(Path.Combine(path, "Merge.txt")))
            foreach (string file in files)
                using (StreamReader reader = System.IO.File.OpenText(file))
                    writer.Write(reader.ReadToEnd() + System.Environment.NewLine);

        return File(System.IO.File.ReadAllBytes(Path.Combine(path, "Merge.txt")), "text / plain", "Merge.txt");


@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
    Layout = null;

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <form asp-controller="Home" method="post" enctype="multipart/form-data">
        <input type="file" name="postedFiles" multiple />
        <input type="submit" value="Merge Text" asp-action="Text" />