Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# StreamReader, "ReadLine" For Custom Delimiters

Tags:

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.

like image 913
Eric Avatar asked Mar 26 '12 13:03

Eric


1 Answers

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();
}
like image 180
Eric Avatar answered Sep 21 '22 14:09

Eric