Stream Reader Readline detect newline characters

后端 未结 3 578
无人共我
无人共我 2021-01-16 17:19

I\'m trying to remove any \"new line\" characters from each line of text in my log file.

Below is an example entry that I am reading in with a Stream Reader :-

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-16 17:46

    The call to Replace isn't working because of this detail from the MSDN doc of StreamReader.ReadLine:

    A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed.

    So if you're going to use StreamReader.ReadLine to read in the input, you could build up a new string with StringBuilder.Append (not AppendLine) as StreamReader.ReadLine implicitly removes the new line characters.

    var filePath = "text.txt";
    StringBuilder sb = new StringBuilder();
    
    using (StreamReader reader = new StreamReader(filePath))
    {
        while (!reader.EndOfStream)
        {
            sb.Append(reader.ReadLine());
        }
    }
    
    File.WriteAllText(filePath, sb.ToString());
    

提交回复
热议问题