C# StreamReader, “ReadLine” For Custom Delimiters

前端 未结 4 712
长发绾君心
长发绾君心 2021-02-18 22:13

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:

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-18 22:55

        public static String ReadUntil(this StreamReader streamReader, String delimiter)
        {
            StringBuilder stringBuilder = new StringBuilder();
    
            while (!streamReader.EndOfStream)
            {
                stringBuilder.Append(value: (Char) streamReader.Read());
    
                if (stringBuilder.ToString().EndsWith(value: delimiter))
                {
                    stringBuilder.Remove(stringBuilder.Length - delimiter.Length, delimiter.Length);
                    break;
                }
            }
    
            return stringBuilder.ToString();
        }
    

提交回复
热议问题