How to read text file by particular line separator character?

后端 未结 9 2016
独厮守ぢ
独厮守ぢ 2020-12-03 00:58

Reading a text file using streamreader.

using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
     string line = sr.ReadLine();
}
<         


        
9条回答
  •  无人及你
    2020-12-03 01:44

    You either have to parse the stream byte-by-byte yourself and handle the split, or you need to use the default ReadLine behavior which splits on /r, /n, or /r/n.

    If you want to parse the stream byte-by-byte, I'd use something like the following extension method:

     public static string ReadToChar(this StreamReader sr, char splitCharacter)
        {        
            char nextChar;
            StringBuilder line = new StringBuilder();
            while (sr.Peek() > 0)
            {               
                nextChar = (char)sr.Read();
                if (nextChar == splitCharacter) return line.ToString();
                line.Append(nextChar);
            }
    
            return line.Length == 0 ? null : line.ToString();
        }
    

提交回复
热议问题