Search code examples
asp.netasp.net-mvcfilestream

Uploading text from file directly in to Database asp.net5 MVC 6


Right know I get an IFormFile to my controller save it in a temp folder and then I use the System.IO.File.ReadAllText to get to the text in the file and store that in my database. After that I delete the file again. Is there a way that I can skip the whole saving part and get the text out of the IFormFile directly?

    [HttpPost]
    public ActionResult Upload(ViewModel model)
    {
        model.file.SaveAsAsync(@"c:\temp\temp.txt");
        String txt= System.IO.File.ReadAllText(@"c:\Temp\temp.txt ");
        db.saveText(txt);
        System.IO.File.Delete(@"c:\Temp\temp.txt ");

        return Redirect("/Home");
    }

Thanks in advance.


Solution

  • This can be done using httpPostedFileBase class returns the HttpInputStreamObject as per specified here

    You should convert the stream into byte array and then you can read file content

    Please refer following link

    http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx

    Hope this helps