To Convert String to Stream in C# and VB.NET you can use the following snippet.

Sample C#

//when using this method, put StringToStream in a using construct
public static Stream StringToStream(string input, Encoding enc)
{
	var memoryStream = new MemoryStream();
	var streamWriter = new StreamWriter(memoryStream,enc);
	streamWriter.Write(input);
	streamWriter.Flush();
	memoryStream.Position = 0;
	return memoryStream;
}

Sample VB.NET

'when using this method, put StringToStream in a using construct
Public Shared Function StringToStream(input As String, enc As Encoding) As Stream
	Dim memoryStream = New MemoryStream()
	Dim streamWriter = New StreamWriter(memoryStream, enc)
	streamWriter.Write(input)
	streamWriter.Flush()
	memoryStream.Position = 0
	Return memoryStream
End Function

2 thought on “How to Convert String to Stream in C# and VB.NET”

Leave a Reply