C# StreamReader, "ReadLine" For Custom Delimiters

Eric picture Eric · Mar 26, 2012 · Viewed 11.4k times · Source

What is the best way to have the functionality of the StreamReader.ReadLine() method, but with custom (String) delimiters?

I'd like to do something like:

String text;
while((text = myStreamReader.ReadUntil("my_delim")) != null)
{
   Console.WriteLine(text);
}

I attempted to make my own using Peek() and StringBuilder, but it's too inefficient. I'm looking for suggestions or possibly an open-source solution.

Thanks.

Edit

I should have clarified this earlier...I have seen this answer, however, I'd prefer not to read the entire file into memory.

Answer

Eric picture Eric · Mar 27, 2012

I figured I would post my own solution. It seems to work pretty well and the code is relatively simple. Feel free to comment.

public static String ReadUntil(this StreamReader sr, String delim)
{
    StringBuilder sb = new StringBuilder();
    bool found = false;

    while (!found && !sr.EndOfStream)
    {
       for (int i = 0; i < delim.Length; i++)
       {
           Char c = (char)sr.Read();
           sb.Append(c);

           if (c != delim[i])
               break;

           if (i == delim.Length - 1)
           {
               sb.Remove(sb.Length - delim.Length, delim.Length);
               found = true;
           }
        }
     }

     return sb.ToString();
}