String Streams in .Net

I while ago (almost 2 years) I posted a way to create a string stream in .Net. There has been a number of new comments added to that post recently so I figured I needed to update that example. Most API's that look for a Stream will also allow either a TextReader or TextWriter depending on the context. Therefore, in those cases when you have a string using StringReader or StringWriter is probably better then creating a MemoryStream like in my old example because you don't have to deal with the encoding.

Example if all you have is a string xmlString then prefer this:

xmlSerializer.Deserialize(new StringReader(xmlString));

instead of this:

xmlSerializer.Deserialize(new MemoryStream(ASCIIEncoding.Default.GetBytes(xmlString)));
Published Monday, September 04, 2006 8:02 PM by puzzlehacker
Filed under: , ,

Comments

# re: String Streams in .Net

If you are using C# 2 a better technique is using IEnumerable and the new yield return. private string[] myData; public IEnumerable GetMyData() { foreach (string s in myData) yield return s; } Now you can consume in somewhere else like foreach (string s in GetMyData()) { //Do something with s } You can do pipelines very easily with iterators, such as: string[] _myData foreach (string s in Job1(Job2(Job3(myData)))) { // do something with s } In the above pipeline, each Job(1/2/3) takes a single parameter as a IEnumerable and returns type IEnumerable Very very efficient. Hope that helps. David

Tuesday, September 05, 2006 4:46 AM by David Taylor

# re: String Streams in .Net

Sorry...I just re-read your post. You dont want string streams, you want a character stream created from a string ;-) My initial response, while interesting, is not relevant.

Tuesday, September 05, 2006 4:49 AM by David Taylor

# Interesting Finds: September 5, 2006

Tuesday, September 05, 2006 11:50 PM by Jason Haley

# String Streams in .Net

Pingback from  String Streams in .Net

Monday, November 26, 2007 6:16 PM by String Streams in .Net

Leave a Comment

(required) 
(required) 
(optional)
(required)