2

I am using FileHelpers to parse CSV files uploaded on an ASP.NET app.

Two different CSV file structures (ie. different amount of columns) will be uploaded, so before I create the FileHelpers engine with the model of the structure to be parsed, I read the first line of the file like this:

string line = "";

using (StreamReader reader = new StreamReader(file.InputStream))
{
    line = reader.ReadLine();
}

int fieldCount = line.Count(l => l == ',');

This works, and gives me the column count, but it breaks anything else I want to do with file.InputStream:

var engine = new FileHelperEngine<CSVModel>();
CSVModel[] records;
records = (CSVModel[])engine.ReadStream(new StreamReader(file.InputStream),
    Int32.MaxValue);
// etc etc

Why does this happen? I've tried to take away the using and just manually close() the StreamReader but it doesn't help.

notAnonymousAnymore
  • 2,637
  • 9
  • 49
  • 74

2 Answers2

1

The problem you're experiencing is because the built in Stream classes dispose the underlying stream once they themselves are disposed or closed.

As counter-intuitive as it is, you'll either need to not close the stream if you're still using it, re-open it before accessing it, or copy it into a MemorStream if you want to use it in more than one place.

This question has some explanations.

Edit: (After Jim's comment)

Alternatively you can inform the StreamReader not to close the underlying stream by using a parameter in the constructor. (MSDN Documentation)

Community
  • 1
  • 1
Matthew Steeples
  • 7,858
  • 4
  • 34
  • 49
0

You should reset the position of the stream after the first read:

file.InputStream.Position = 0;
Alberto
  • 15,626
  • 9
  • 43
  • 56
  • That will not work. `StreamReader` has an internal buffer. So if you reset the underlying stream's position, things will get all jumbled the next time the `StreamReader` goes to update its buffer. – Jim Mischel Sep 18 '13 at 16:10