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 asp.net core.

Posted 8 days ago

Hi rani,

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

Namespaces

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;

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 Text(List<IFormFile> postedFiles)
    {
        string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(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))
            {
                postedFile.CopyTo(stream);
                files.Add(filePath);
            }
        }

        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");
    }
}

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 Text" asp-action="Text" />
    </form>
</body>
</html>