2

I have a website that posts a large file to my server. I need to read it line by line or at least be able to split it. It's 2000 pages long.

Right now, I have :

if (file != null && file.ContentLength > 0)
                {
                    using (file.InputStream)
                    {
                       //Looking for this part
                    }
                }

Thanks,

Phil

MusicAndCode
  • 870
  • 8
  • 22

2 Answers2

2

I followed @Gusman's idea of using the streamreader.

stream = new StreamReader(file.InputStream);
using (stream)
{
    while (stream.Peek() >= 0)
    {
        var line =  stream.ReadLine();
        //some stuff              
    }
}

Thanks also @Ali

MusicAndCode
  • 870
  • 8
  • 22
1

Try this:

public IEnumerable<string> ReadLines(Func<Stream> streamProvider,
                                     Encoding encoding)
{
    using (var stream = streamProvider())
    using (var reader = new StreamReader(stream, encoding))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

So :

var lines = ReadLines(() => file.InputStream, Encoding.UTF8).ToArray();

I hope to be helpful

Ali Adlavaran
  • 3,697
  • 2
  • 23
  • 47
  • that defeats the purpose of the user, that will return all lines in an array, is exactly the same as `File.ReadAllLines` but with a lot of overhead, the user wants to read it line by line to process it and not have all the file on memory. – Gusman Aug 01 '17 at 19:12
  • @Gusman It will not, it will return one line at a time from the stream. It returns an IEnumerable not an array. (Original code from here: https://stackoverflow.com/a/13312954/468973) – Magnus Aug 01 '17 at 19:14
  • so I return `yield return line` and It could be enumerate and It could be run with `ToArray` – Ali Adlavaran Aug 01 '17 at 19:15
  • 1
    Ok, I read it wrong, sorry. Anyway an streamreader would be a lot more easy and the default way – Gusman Aug 01 '17 at 19:16