[file] ASP.Net MVC - Read File from HttpPostedFileBase without save

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?

This question is related to file c#-4.0 file-io asp.net-mvc-2 stream

The answer is


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

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


An alternative is to use StreamReader.

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

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

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to c#-4.0

Xml Parsing in C# EPPlus - Read Excel Table How to add and get Header values in WebApi How to make all controls resize accordingly proportionally when window is maximized? How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project How to get first record in each group using Linq How to get first object out from List<Object> using Linq ASP.Net MVC - Read File from HttpPostedFileBase without save .NET NewtonSoft JSON deserialize map to a different property name Datetime in C# add days

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js

Examples related to asp.net-mvc-2

Better solution without exluding fields from Binding How to set the value of a hidden field from a controller in mvc Making a Simple Ajax call to controller in asp.net mvc ASP.Net MVC - Read File from HttpPostedFileBase without save Session state can only be used when enableSessionState is set to true either in a configuration Using Tempdata in ASP.NET MVC - Best practice Getting index value on razor foreach Current date and time - Default in MVC razor Url.Action parameters? How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Examples related to stream

Why does calling sumr on a stream with 50 tuples not complete How to read/write files in .Net Core? How to get the stream key for twitch.tv Download TS files from video stream How to get streaming url from online streaming radio station Save byte array to file How to get error message when ifstream open fails Download large file in python with requests ASP.Net MVC - Read File from HttpPostedFileBase without save Fastest way to check if a file exist using standard C++/C++11/C?