简体   繁体   中英

Replacing a Stream with a String in a C# program

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

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

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

您可以使用MemoryStream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM