asp.net MVC

How to read text file using fileupload control in asp.net MVC?

How to read text file using fileupload control in asp.net MVC?, someone asked me to explain?

In this step by step article describes how to read text file using fileupload control in asp.net MVC.create a post form method with html controls file, button and create a folder name with Document in the project. When user choose the text file and click the submit button the controller will receive file type, name etc. we will save the file in our project document folder.

Using stream reader we will read the file with the help of file path. The reader will read the file line by line we are assigning to stringbuilder by appending. Finally we are returning as JsonResult. 

SQL Script Data

Example:

Step 1: Right clicks on the "Controllers" folder and add "fileUpload" controller. Copy and paste the following code.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace MVC_tutorials.Controllers
{
    public class fileUploadController : Controller
    {
       // GET: /file/
        public ActionResult Index()
        {
            return View();
        }
       [System.Web.Mvc.HttpPost]
        public JsonResult upload(HttpPostedFileBase file)
        {
            bool result = false;
            StringBuilder strbuild = new StringBuilder();
            try
            {
                if (file.ContentLength == 0)
                   throw new Exception("Zero length file!");
                else
               {
                   var fileName = Path.GetFileName(file.FileName);
                   var filePath = Path.Combine(Server.MapPath("~/Document"), fileName);
                   file.SaveAs(filePath);
                     if (!string.IsNullOrEmpty(filePath))
                   {
                       using (StreamReader sr = new StreamReader(Path.Combine(Server.MapPath("~/Document"), fileName)))
                       {
                            while (sr.Peek() >= 0)
                            {
                               strbuild.AppendFormat(sr.ReadLine());
                            }
                       }
                    }
              }
             }
            catch (Exception)
            {
               result = false;
            }
 
            return new JsonResult()
               {
                   Data = strbuild.ToString()
               };
        }
 
    }
}

Step 2: Right click on the "Index" action method in the "fileUploadController" and add "Index" view. Copy and paste the following code. 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Read text fileusing asp.net MVC</title>
    <style type="text/css">
        .btn {
            width: 100px;
            height: 50px;
            background: #00BCD4;
            border-style: solid;
            border-color: white;
            color: white;
        }
    </style>
</head>

<body style="border: 1px solid #DED8D8; width: 500px; height: 300px; font-family: Arial; margin-left: 50px">
    @using (@Html.BeginForm("upload", "fileUpload", FormMethod.Post,
     new { enctype = "multipart/form-data" }))
    {
        if (TempData["Message"] != null)
        {
        <p style="font-family: Arial; font-size: 16px; font-weight: 200; color: red">@TempData["Message"]</p>
        }
        <table>
            <tr>
                <td style="padding-bottom: 35px" colspan="2">
                   <h2 style="color: #FF5722">Read text file using asp.net MVC</h2>
                </td>
            </tr>
            <tr>
                <td style="width: 200px;">
                   <b style="color: #FF5722">choose Text file:</b>
                </td>
                <td>
                   <input type="file" name="file" id="file" />
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td colspan="2" style="padding-top: 30px">
                   <input type="submit" class="btn" value="Read Text" name="submit" />
               </td>
            </tr>
        </table>
    }
</body>
</html>

 Output:

Read text file using asp.net MVC

Post your comments / questions