StreamReader to read from string?

G

Guest

Hi,

Im using a code snippet that reads a text file from disc and processes it
using

stream = new StreamReader(filename);

Is it possible to assign a String instead of a file as the source of the
stream, and if yes, how?

Regards
Jesper.
 
J

Jon Skeet [C# MVP]

Jesper said:
Im using a code snippet that reads a text file from disc and processes it
using

stream = new StreamReader(filename);

Is it possible to assign a String instead of a file as the source of the
stream, and if yes, how?

Well, not for a StreamReader (easily) - but if all you need is a
*TextReader* (which is probable) just use StringReader instead.

Jon
 
M

Maqsood Ahmed

Hello,
Yes you can, convert the string in to byte array using
System.Text.Encoding.ASCII.GetBytes method. Then pass those bytes to
MemoryStream class's constructor. You'll get and Stream object, but it
won't be of 'StreamReader' type.

HTH. Cheers.

Maqsood Ahmed - MCAD.net
Kolachi Advanced Technologies
http://www.kolachi.net
 
J

Jon Skeet [C# MVP]

Maqsood said:
Yes you can, convert the string in to byte array using
System.Text.Encoding.ASCII.GetBytes method. Then pass those bytes to
MemoryStream class's constructor. You'll get and Stream object, but it
won't be of 'StreamReader' type.

That's a really bad idea unless you've got solely ASCII characters.
You should at least use something which preserves Unicode characters -
eg Encoding.UTF8. (That also happens to be the default encoding used by
StreamReader...)

Jon
 
J

Jon Skeet [C# MVP]

Maqsood Ahmed said:
Yes, it was just to *tell* :) it all depends upon the requirements of
the problem.

Unfortunately, in my experience if you specify a "solution" which
doesn't explain its own limitations, people tend to use it without
questioning whether or not it's actually fit for purpose :(
 

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