C# tip: A quick and easy way to read a stream and convert it to a string

Posted: (EET/GMT+2)

 

While coding .NET application with C#, I find myself quite often in a situation where I need to take a stream object (usually from the result of a web query/web API call), and convert that into a string.

The conversion process requires several simple steps, but repeating them all the time is tedious. Thus, I've written myself a simple extension method called "ReadToEnd" that takes a stream object and converts it to a string.

Here's the code:

internal static string ReadToEnd(this Stream stream)
{
    int length = (int)stream.Length;
    byte[] buffer = new byte[length];
    int bytesRead = stream.Read(buffer, 0, length);
    string data = Encoding.UTF8.GetString(buffer,
      0, bytesRead);
    return data;
}

This routine assumes three things: the whole stream should be converted into a string, that the data is in UTF-8 (UTF8, code page 65001) format, and isn't overly long (will easily fit into memory). If all these three assumptions fit your needs, then this routine is probably easy to copy into your own utility routines as well.

Hope this helps!

Keywords: Stream to string, Convert stream bytes into an UTF-8 string, C#, .NET, extension methods, read stream to end