Using a Stream Extension Method to Read Directly from a Stream into a String
Quick post to show how an extension method can be used to read from a stream into a string. I’ve tried this extension method with memory and file streams and it works fine.
The code is self explanatory, so I won’t add anything else.
1using System.Text;
2
3public static class ExtensionMethods
4{
5 public static string StreamToString(this Stream stream)
6 {
7 using (StreamReader streamReader = new StreamReader(stream))
8 {
9 string text = streamReader.ReadToEnd();
10 return text;
11 };
12 }
13}
14
15public class Program {
16 public static void Main(string[] args) {
17
18 // string to byte array, byte array to memory stream, memory stream to string
19 byte[] someText = Encoding.ASCII.GetBytes("hello world from a string");
20 MemoryStream someTextInAMemoryStream = new MemoryStream(someText);
21 Console.WriteLine(someTextInAMemoryStream.StreamToString());
22
23 // file to byte array, byte array to memory stream, memory stream to string
24 byte[] file = File.ReadAllBytes("hello.txt");
25 MemoryStream fileInAMemoryStream = new MemoryStream(file);
26 Console.WriteLine(fileInAMemoryStream.StreamToString());
27
28 // file to file stream, file stream to string
29 FileStream fileStream = new FileStream("goodbye.txt", FileMode.Open);
30 Console.WriteLine(fileStream.StreamToString());
31
32 // for the record, you can read a file directly into a stream reader
33 using (var streamReader = new StreamReader("hello.txt")) {
34 Console.WriteLine(streamReader.BaseStream.StreamToString());
35 }
36 }
37}