How to read text file by particular line separator character?

后端 未结 9 2003
独厮守ぢ
独厮守ぢ 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:41

    This code snippet will read a line from a file until it encounters "\n".

    using (StreamReader sr = new StreamReader(path)) 
    {
         string line = string.Empty;
         while (sr.Peek() >= 0) 
         {
              char c = (char)sr.Read();
              if (c == '\n')
              {
                  //end of line encountered
                  Console.WriteLine(line);
                  //create new line
                  line = string.Empty;
              }
              else
              {
                   line += (char)sr.Read();
              }
         }
    }
    

    Because this code reads character by character it will work with a file of any length without being constrained by available memory.

提交回复
热议问题