tags:

views:

75

answers:

3

Currently, I have a program that reads a file and uses an XMLTextWriter to write an XML file to disk. Shortly afterward, I read the file and parse it.

I am trying to put these two programs together. I want to get rid of the writing to file step. The XMLTextWriter needs a file path or a Stream when it is constructed. Is there a way to make a Stream that will create a string with the output instead of writing it to a file?

Thanks

+1  A: 

You can use a MemoryStream.

Robert Harvey
+4  A: 

The simplest way is to use a MemoryStream:

// To give code something to read
Stream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(text));
CallRealCode(memoryStream);


// To give code something to write:
Stream memoryStream = new MemoryStream();
CallRealCode(memoryStream);
string text = Encoding.UTF8.GetString(memoryStream.ToArray());

(Adjust to an appropriate encoding, of course.)

Alternatively, if you can provide your code with a TextWriter instead of a Stream, you could use a StringWriter. One point to note is that by default, StringWriter will advertise itself as wanting to use UTF-16. You can override this behaviour with a subclass, like this:

public sealed class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding { get { return Encoding.UTF8; } }
}

(Obviously you could do this in a more flexible way, too...)

Jon Skeet
+3  A: 

The XmlTextWriter also has a constructor that can take a TextWriter, so you can simply use a StringWriter:

string xml;
using (StringWriter str = new StringWriter()) {
  using (XmlTextWriter writer = new XmlTextWriter(str)) {
    // write the XML
  }
  xml = str.ToString();
}
Guffa