ASP.Net MVC - Read File from HttpPostedFileBase without save

FileC# 4.0File Ioasp.net Mvc-2Stream

File Problem Overview


I am uploading the file by using file upload option. And i am directly send this file from View to Controller in POST method like,

    [HttpPost]
    public ActionResult Page2(FormCollection objCollection)
    {
        HttpPostedFileBase file = Request.Files[0];
    }

Assume, i am uploading a notepad file. How do i read this file & append this text to string builder,, without save that file....

I'm aware about after SaveAs this file, we can read this file. But How do i read this file from HttpPostedFileBase without save?

File Solutions


Solution 1 - File

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

UPDATE :

> The stream that you get from your HTTP call is read-only sequential > (non-seekable) and the FileStream is read/write seekable. You will > need first to read the entire stream from the HTTP call into a byte > array, then create the FileStream from that array.

Taken from here

// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);

string result = System.Text.Encoding.UTF8.GetString(binData);

Solution 2 - File

An alternative is to use StreamReader.

public void FunctionName(HttpPostedFileBase file)
{
    string result = new StreamReader(file.InputStream).ReadToEnd();
}

Solution 3 - File

A slight change to Thangamani Palanisamy answer, which allows the Binary reader to be disposed and corrects the input length issue in his comments.

string result = string.Empty;

using (BinaryReader b = new BinaryReader(file.InputStream))
{
  byte[] binData = b.ReadBytes(file.ContentLength);
  result = System.Text.Encoding.UTF8.GetString(binData);
}

Solution 4 - File

byte[] data; using(Stream inputStream=file.InputStream) { MemoryStream memoryStream = inputStream as MemoryStream; if (memoryStream == null) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } data = memoryStream.ToArray(); }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionManikandan SethurajuView Question on Stackoverflow
Solution 1 - FileThangamani PalanisamyView Answer on Stackoverflow
Solution 2 - FileRichard YSView Answer on Stackoverflow
Solution 3 - FileStigView Answer on Stackoverflow
Solution 4 - FileJawad RazaView Answer on Stackoverflow