StreamWriter add an extra \\r in the end of the line

安稳与你 提交于 2019-12-01 17:58:40

My guess is that the extra \r is added during FTP (maybe try a binary transfer)

Like here

I've tested the code and the extra /r is not due to the code in the current question

According to MSDN, WriteLine

Writes data followed by a line terminator to the text string or stream.

your last line should be

 _streamWriter.Write(line);

Put it outside of your loop and change your loop so it doesn't manage the last line.

I had a similar issue. Environment.NewLine and WriteLine gave me extra \r character. But this below worked for me:

StringBuilder sbFileContent = new StringBuilder();
sbFileContent.Append(line);
sbFileContent.Append("\n");
streamWriter.Write(sbFileContent.ToString());

I just now had a similar problem where the code below would randomly insert blank lines in the output file (outFile)

using (StreamWriter outFile = new StreamWriter(outFilePath, true)) {
     foreach (string line in File.ReadLines(logPath)) {
            string concatLine = parse(line, out bool shouldWrite);
            if (shouldWrite) {
              outFile.WriteLine(concatLine);       
            }     
      }   
}

Using Antar's idea I changed my parse function so that it returned a line with Environment.NewLine appended, ie

return myStringBuilder.Append(Environment.NewLine).ToString();

and then in the foreach loop above, changed the

outFile.WriteLine(concatLine);

to

outFile.Write(concatLine);

and now it writes the file without a bunch of random new lines inserted. However, I still have absolutely no idea why I should have to do this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!