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)));


  • 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.


  • 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.

Comments have been disabled for this content.