Before saving the downloaded CSV file, I want to check whether it will be parsed. When I just saved the file, everything was in order, now when I read it, the saved file is empty first.
Here is my action method
[HttpPost] public ActionResult Import(HttpPostedFileBase file) { // Check parse went ok using (var fileStream = file.InputStream) { if (!MemberFileParsingService.CheckFileWillParse(fileStream)) { ViewBag.Message = "There was a problem with the file"; return View(); } } // Save file so we can work on it in next action file.SaveAs(Server.MapPath(fileName)); return RedirectToAction("ImportMatch", new { club = ActiveClub.Url }); }
And here is my method that checks if the file is well parsed. It uses CsvReader to read the entire file to check for errors. CsvReader throws exceptions when it comes to bad file bits.
public static bool CheckFileWillParse(Stream fileStream) { try { using (var reader = new StreamReader(fileStream)) { using (CsvReader csv = new CsvReader(reader, false)) { while (csv.ReadNextRecord()) { } } } } catch(Exception) { return false; } return true; }
I think this is possible because it is trying to write the file using the same stream that is now at the end of the file. However, I do not know how to reset the stream. I was hoping all my operators would fix this problem.
So, how can I reset the thread, or is it just a red herring?
Update:. The found stream length gets reset to zero after passing CheckFileWillParse, so it seems that resetting the stream is just a red herring, and the stream will actually somehow close.
source share