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

前端 未结 4 1914
我在风中等你
我在风中等你 2021-01-18 08:32

I created a class with the responsibility to generate a text file where each line represents the information of an object of \'MyDataClass\' class. Below is a simplification

相关标签:
4条回答
  • 2021-01-18 09:09

    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

    0 讨论(0)
  • 2021-01-18 09:18

    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());
    
    0 讨论(0)
  • 2021-01-18 09:23

    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.

    0 讨论(0)
  • 2021-01-18 09:30

    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.

    0 讨论(0)
提交回复
热议问题