How to Convert Stream to Strings in C#?
A stream in C# is a sequence of bytes, and converting it to a string involves decoding these bytes using a specified character encoding. The StreamReader
class, available in the System.IO
namespace, is commonly used for reading streams and decoding the byte data into characters.
Let's consider a scenario where we have a text file named "sample.txt" containing some text. Our goal is to read this file as a stream and convert it into a string.
using System;
using System.IO;
using System.Text;
class StreamToStringConverter
{
static void Main()
{
// Specify the file path
string filePath = "sample.txt";
// Read the stream from the file
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
// Specify the encoding (UTF-8 in this case)
Encoding encoding = Encoding.UTF8;
// Create a StreamReader
using (StreamReader streamReader = new StreamReader(fileStream, encoding))
{
// Read the stream and convert it to a string
string result = streamReader.ReadToEnd();
// Display the converted string
Console.WriteLine("Converted String:\n" + result);
}
}
}
}
Output:
Assuming the "sample.txt" file contains the text "Hello, C# Stream Conversion!", the output of the program will be:
Converted String:
Hello, C# Stream Conversion!
Comments (0)