写入文件流时在字节序列中添加换行符

时间:2018-08-23 19:05:34

标签: c# encoding filestream

我正在写Newline时添加FileStream,即使我尝试了,似乎也是如此:
\r\n
\\r\\n
System.Environment.Newline
结果文件不会添加换行符,而只会按原样添加字符:

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);
 }

在我们的情况下,NewLineSystem.Environment.Newline,但是我已经尝试了所有上述组合,并且文件的输出是:

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

我想要

 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;
        }

1 个答案:

答案 0 :(得分:1)

您正在将字符串传递到ToMemory,该字符串将其转换为JSON。然后,JSON序列化程序正确地转义换行符。

解决方法似乎是根本不编码为JSON。将字符串直接写入流中。