DEV Community

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

Posted on

2 1

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)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay