title: Reading a file line by line in C#
body: <p>I am trying to read some text files, where each line needs to be processed. At the moment I am just using a StreamReader, and then reading each line individually.</p>
  
  <p>I am wondering whether there is a more efficient way (in terms of LoC and readability) to do this using LINQ without compromising operational efficiency. The examples I have seen involve loading the whole file into memory, and then processing it. In this case however I don't believe that would be very efficient. In the first example the files can get up to about 50k, and in the second example, not all lines of the file need to be read (sizes are typically &lt; 10k).</p>
  
  <p>You could argue that nowadays it doesn't really matter for these small files, however I believe that sort of the approach leads to inefficient code.</p>
  
  <p>First example:</p>
  
  <pre><code>// Open file
  using(var file = System.IO.File.OpenText(_LstFilename))
  {
      // Read file
      while (!file.EndOfStream)
      {
          String line = file.ReadLine();
  
          // Ignore empty lines
          if (line.Length &gt; 0)
          {
              // Create addon
              T addon = new T();
              addon.Load(line, _BaseDir);
  
              // Add to collection
              collection.Add(addon);
          }
      }
  }
  </code></pre>
  
  <p>Second example:</p>
  
  <pre><code>// Open file
  using (var file = System.IO.File.OpenText(datFile))
  {
      // Compile regexs
      Regex nameRegex = new Regex("IDENTIFY (.*)");
  
      while (!file.EndOfStream)
      {
          String line = file.ReadLine();
  
          // Check name
          Match m = nameRegex.Match(line);
          if (m.Success)
          {
              _Name = m.Groups[1].Value;
  
              // Remove me when other values are read
              break;
          }
      }
  }
  </code></pre>