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?
source share