Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# StringWriter与StreamWriter包装内存流-差异_C#_.net - Fatal编程技术网

C# StringWriter与StreamWriter包装内存流-差异

C# StringWriter与StreamWriter包装内存流-差异,c#,.net,C#,.net,我有以下代码: byte[] snapthotBytes, snapthotBytes2; string stringOutput, stringOutput2; IInvestigationDump investigationDump = new HtmlSnapshotDump(); using (TextWriter writer = new StringWriter()) { inve

我有以下代码:

        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方法只遍历调查对象并呈现HTML报告(通过写入writer对象)
  • 从StringWriter使用UTF-16编码和XML声明的事实来看,stringOutput和stringOutput2应该具有相同的内容转储方法签名为:
void Dump(调查、文本编写)

  • Dump方法只写入写入器,不带任何条件等
起初我使用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()
在尝试读取流之前?

如何

writer.Flush()

在尝试阅读流之前?

你一定是在跟我开玩笑!:)成功了。但是为什么呢?你能详细说明一下吗?我没有想到在写入MemoryStream时应该进行刷新。我的意思是为什么在这种特殊情况下必须进行刷新:)这是因为StreamWriter缓冲输入,并且仅在缓冲区已满时进行刷新,以便它可以更有效地写入底层流。MemoryStream和其他类型的流没有区别。你一定是在开玩笑吧!:)成功了。但是为什么呢?你能详细说明一下吗?我没有想到在写入MemoryStream时应该进行刷新。我的意思是为什么在这种特殊情况下必须进行刷新:)这是因为StreamWriter缓冲输入,并且仅在缓冲区已满时进行刷新,以便它可以更有效地写入底层流。MemoryStream和其他类型的流之间没有区别。