c# - StringWriter 与 StreamWriter 包装 MemoryStream - 区别

标签 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

一些介绍:

  • 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/

相关文章:

.net - 使用 ExecuteNonQuery 覆盖 SQL Server 中受影响的行?

c# - WPF 从 TreeView 中移除 ScrollViewer

c# - 如果存在某个属性,则加载程序集

c# - 如何使用反射在静态类中查找私有(private)静态方法?

c# - C# 中 azure 的组合缓存提供程序

c# - 如何使用 PaintEventArgs 参数调用函数?

c# - 编写一个函数来比较两个字符串并返回第三个字符串,该字符串仅包含出现在两个字符串中的字母

c# - 跨多个方法使用 SQLConnection ('using' 关键字是或否)

c# - 想要一个用于传入数据的 .Net 套接字事件处理程序

c# - 将 Realm 同步与 Azure Functions 结合使用