Search code examples
c#encodingfilestream

Adding newline to byte sequence when writing to filestream


I am trying to add Newline when writing to a FileStream and it seems that even if i try :
\r\n or
\\r\\n or
System.Environment.Newline
the result file will not add the newlines.It will just add the characters as they are:

public static NewLine=>System.Environment.Newline;

 string header = $"Client:{index}{Newline}Date:{DateTime.Now.ToString()}{Newline}\r\nData:{Newline}";
 using (FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate,FileAccess.ReadWrite, FileShare.ReadWrite))   
 {
    await stream.WriteAsync(header.ToMemory());

    ReadOnlyMemory<byte> memory = Enumerable.Aggregate(
                                    responses,
                                    string.Empty,
                                    (acc, src) => acc + Newline + src.ToString()).ToMemory();
    await stream.WriteAsync(memory);
 }

In our case NewLine is System.Environment.Newline, but i have tried all of the above combinations and the output of the file is:

"Client:0\r\nDate:23.08.2018 21:56:04\r\n\r\nData:\r\n""\r\n00:00:00.3222976"510"

And i wanted

 Client:0
 Date:23.08.2018 
 Data:  --data should start from below
 00:00:00.3222976 510
 .........

ToMemory

 public static ReadOnlyMemory<byte> ToMemory(this object obj)
        {
            string dataString = JsonConvert.SerializeObject(obj);
            ReadOnlyMemory<byte> dataBytes = Encoding.UTF8.GetBytes(dataString);
            return dataBytes;
        }

Solution

  • You're passing a string to ToMemory which converts it to JSON. The JSON serializer then, correctly, escapes the newline characters.

    The fix seems to be to simply not encode as JSON. Write the string to the stream directly.