StringWriter与StreamWriter包装MemoryStream - 区别

时间:2011-12-01 10:36:47

标签: c# .net

我有以下代码:

        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

一些介绍:

  • 转储方法只遍历调查对象并呈现HTML报告(通过写入编写器对象)。
  • Appart从StringWriter使用UTF-16编码和XML声明的事实将有所不同,stringOutput& stringOutput2应具有相同的内容。 转储方法签名是:

void Dump(IInvestigation investigation, TextWriter 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 

1 个答案:

答案 0 :(得分:5)

怎么样

writer.Flush()

在尝试阅读流之前?