Good morning - I am attempting to save an HttpPostedFileBase (which will always be a simple CSV file) to a session variable like so:
[HttpPost]
public ActionResult Index(HttpPostedFileBase importFile) {
Session.Remove("NoteImport");
var noteImport = new NoteImport { ImportFile = importFile, HeaderList = NoteService.HeaderList(importFile) };
Session["NoteImport"] = noteImport;
return RedirectToAction("FileNote");
}
As you see, I am dumping importFile into my NoteImport class. Currently, the ImportFile property is a publicly accessible HttpPostedFileBase type.
The first time I use this property in my service (method that creates a list of header values), I have no problem:
public List<string> HeaderList(HttpPostedFileBase fileStream) {
var sr = new StreamReader(fileStream.InputStream);
var headerString = sr.ReadLine();
var headerArray = headerString.Split(',');
var headerList = new List<string>();
foreach (var header in headerArray) {
if (!ValidateHeader(header))
throw new InvalidDataException("Invalid header name: " + header);
headerList.Add(header);
}
return headerList;
}
The above works fine and returns exactly what I need for the time being.
My problem is with the code below. When I call ReadLine(), it doesn't get anything out of the HttpPostedFileBase.
public List<string> ImportFileStream(HttpPostedFileBase importFile) {
var sr = new StreamReader(importFile.InputStream);
var headerString = sr.ReadLine();
var headerArray = headerString.Split(',');
var cb = new DelimitedClassBuilder("temp", ",") { IgnoreFirstLines = 0, IgnoreEmptyLines = true, Delimiter = "," };
foreach (var header in headerArray) {
cb.AddField(header, typeof(string));
cb.LastField.FieldQuoted = true;
cb.LastField.QuoteChar = '"';
}
var engine = new FileHelperEngine(cb.CreateRecordClass());
var dataTable = engine.ReadStreamAsDT(sr);
var noteData = new List<string>();
var jsonSerializer = new JsonSerializeDataRow();
foreach (var row in dataTable.Rows) {
var dataRow = row as DataRow;
var jsonRow = jsonSerializer.Serialize(dataRow);
noteData.Add(jsonRow);
}
return noteData;
}
I have attempted closing the HttpPostedFileBase; I have also set the stream position to 0. Nothing seems to be going. I have a feeling I need to change it to a different type before saving to the session.
Any advice??
Thanks!