DEV Community

Félix Dion-Robidoux
Félix Dion-Robidoux

Posted on

PSA: Stop using Streams and Reader/Writers to Convert Strings/ByteArrays

Stop doing this :

using (var memory = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(memory, Encoding.ASCII)) { foreach (var lineData in dataLines) { writer.WriteLine(lineData); } writer.Flush(); return memory.GetBuffer(); } } 
Enter fullscreen mode Exit fullscreen mode

Just... do this instead :

return Encoding.ASCII.GetBytes(lineData.Join("\n\r")); 
Enter fullscreen mode Exit fullscreen mode

Trust me, it's not worth using streams unless you explicitly need to.

Top comments (0)