[英]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. 目前,我有一个程序读取文件并使用XMLTextWriter将XML文件写入磁盘。 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. XMLTextWriter在构造时需要文件路径或Stream。 Is there a way to make a Stream that will create a string with the output instead of writing it to a file? 有没有办法让Stream创建一个带输出的字符串而不是将其写入文件?
Thanks 谢谢
The simplest way is to use a MemoryStream
: 最简单的方法是使用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
. 或者,如果您可以使用TextWriter
而不是Stream
来提供代码,则可以使用StringWriter
。 One point to note is that by default, StringWriter
will advertise itself as wanting to use UTF-16. 需要注意的一点是,默认情况下, StringWriter
会将自己宣传为想要使用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: XmlTextWriter还有一个可以使用TextWriter的构造函数,因此您可以简单地使用StringWriter:
string xml;
using (StringWriter str = new StringWriter()) {
using (XmlTextWriter writer = new XmlTextWriter(str)) {
// write the XML
}
xml = str.ToString();
}
您可以使用MemoryStream 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.