Convert a String into a Stream

G

Guest

Hello,

I'm looking for a solution for convert a variable who is a String into
Stream type. I use VB.Net. Anyone know how convert a STring into a Stream ?

Thanks for your help
Tigrou.
 
T

Tom Dacon

Put the string into a StringBuilder object, then open a TextReader on the
StringBuilder.

Tom Dacon
Dacon Software Consulting
 
M

Morten Wennevik

Hi Tigrou,

Convert the String into a Byte array using Encoding.GetBytes(string) and
feed the array to a MemoryStream.
 
J

Jon Skeet [C# MVP]

Tom Dacon said:
Put the string into a StringBuilder object, then open a TextReader on the
StringBuilder.

If you actually want a TextReader, using StringReader is the way to go
- there's no need to go via a StringBuilder. (I'm not sure how you were
suggesting opening a TextReader on the StringBuilder anyway, to be
honest.)
 
G

Guest

Ok, thanks for all your help :). I will try your solutions and keep the best
for me. Thanks again for your rapidity and for your answer.

Tigrou
 
G

Guest

Hi,

Finally i used byte and memory stream, i put byte into the memoryStream and
at the end i apply CType(myMemoryStream, Stream)
Like this i can convert my String into a Stream.

You can see an example of my code:

Dim myEncoder As New System.Text.ASCIIEncoding
Dim bytes As Byte() = myEncoder.GetBytes(myString)
Dim ms As MemoryStream = New MemoryStream(bytes)

myObjectWhoNeedAStream.Load(CType(ms, Stream))

Thanks again to everybody :)
Bye
 
J

Jon Skeet [C# MVP]

Tigrou said:
Finally i used byte and memory stream, i put byte into the memoryStream and
at the end i apply CType(myMemoryStream, Stream)
Like this i can convert my String into a Stream.

You can see an example of my code:

Dim myEncoder As New System.Text.ASCIIEncoding
Dim bytes As Byte() = myEncoder.GetBytes(myString)
Dim ms As MemoryStream = New MemoryStream(bytes)

myObjectWhoNeedAStream.Load(CType(ms, Stream))

Note that there's no need to create a new instance of ASCIIEncoding.
Just use the one provided by the Encoding.ASCII property:

Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(myString)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top