StreamReader to read from string?

  • Thread starter Thread starter Guest
  • Start date Start date
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.
 
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
 
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
 
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
 
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 :(
 
Back
Top