我有以下代码:
byte[] snapthotBytes, snapthotBytes2;
string stringOutput, stringOutput2;
IInvestigationDump investigationDump = new HtmlSnapshotDump();
using (TextWriter writer = new StringWriter())
{
investigationDump.Dump(investigation, writer);
snapthotBytes = Encoding.UTF8.GetBytes(writer.ToString());
stringOutput = writer.ToString();
} // end of first implementation
using (MemoryStream stream = new MemoryStream())
using (TextWriter writer = new StreamWriter(stream))
{
investigationDump.Dump(investigation, writer);
stream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(stream);
stringOutput2 = reader.ReadToEnd();
snapthotBytes2 = stream.ToArray();
} // end of second implementation
// stringOutput != stringOutput2 - content wise
// snapthotBytes != snapthotBytes2 - content wise
一些介绍:
- Dump 方法只是遍历 investigation 对象并呈现 HTML 报告(通过写入 writer 对象)。
- 除了 StringWriter 使用 UTF-16 编码和 XML 声明会有所不同之外,stringOutput 和 stringOutput2 应该具有相同的内容。 Dump 方法签名是:
void Dump(IInvestigation investigation, TextWriter writer);
- Dump 方法只是写入一个 writer,没有任何条件等。
起初我使用的是 MemoryStream 代码片段,因为我直接收到了 byte[],所以更容易。但很快我意识到了一个错误。令人惊讶的是,stringOutput2(由 MemoryStream 解决方案生成)被修剪了,它更短了!它只是以经过修剪的 HTML 内容结尾:
<tr>
<td>Certificate or License No</td>
<td class="value">Friuan</td>
<td>Place of Issue</td>
<td class="value">Foruan</td>
</tr>
<tr>
<td>Award Date</td>
<td
最佳答案
怎么样
writer.Flush()
在尝试读取流之前?
关于c# - StringWriter 与 StreamWriter 包装 MemoryStream - 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8339941/