File Download: MemoryStream vs. File System

In the business application that I create, we allow our administrators to upload a CSV file with certain data that is analyzed and entered into our databases (all relevant error handling occurs, etc.).

As part of upgrading to .NET 4.5, I had to update several aspects of this code, and while I was doing this, I came across this answer from someone who uses MemoryStream to process downloaded files, and not to temporarily save them to the file system. There is no real reason for me (and maybe it's even bad), but I wanted to give him a chance to learn a little. So, I quickly changed this code (from a strongly typed model due to loading other metadata):

HttpPostedFileBase file = model.File; var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName); file.SaveAs(path); CsvParser csvParser = new CsvParser(); Product product = csvParser.Parse(path); this.repository.Insert(product); this.repository.Save(); return View("Details", product); 

:

 using (MemoryStream memoryStream = new MemoryStream()) { model.File.InputStream.CopyTo(memoryStream); CsvParser csvParser = new CsvParser(); Product product = csvParser.Parse(memoryStream); this.repository.Insert(product); this.repository.Save(); return View("Details", product); } 

Unfortunately, when I do this, everything breaks - all my data is displayed with zero values, and it seems that there is nothing really in the MemoryStream (although I'm not sure about that). I know this can be a long shot, but is there something obvious that I'm missing here or can do something to better debug this?

+4
source share
2 answers

You need to add the following:

 model.File.InputStream.CopyTo(memoryStream); memoryStream.Position = 0; ... Product product = csvParser.Parse(memoryStream); 

When you copy a file to a MemoryStream, the pointer moves to the end of the stream, so when you try to read it, you get a null byte instead of the stream data. You just need to reset the position to the beginning, i.e. 0.

+5
source

I believe that your Stream memory has a position set to the end, and I assume that your CSVParser processes only from the moment when there is no data.

To fix this, you can simply set memoryStream to 0 before parsing it with csvParser.

 memoryStream.Position = 0; 
+1
source

All Articles