【问题标题】:Write one memorystream of UTF8-encoded data to the end of another C#将一个 UTF8 编码数据的内存流写入另一个 C# 的末尾
【发布时间】:2013-10-07 01:53:27
【问题描述】:

我正在尝试将一个内存流的内容附加到另一个内存流的内容,因为我知道两个内存流都包含 UTF8 编码的数据,并在我将组合的内存流转换回来时得到一个 UTF8 字符串。但它不起作用=>第二个内存流被附加为垃圾(或者至少,它没有通过 StreamReader 回来)。会发生什么?

我设置了以下 linqpad 脚本来重现我的问题:

string one = "first memorystream";
string two = ", and the second";

MemoryStream ms = new MemoryStream();
MemoryStream ms2 = new MemoryStream();

byte[] oneb = Encoding.UTF8.GetBytes(one);
byte[] twob = Encoding.UTF8.GetBytes(two);

ms.Write(oneb, 0, oneb.Length);
ms2.Write(twob, 0, twob.Length);

ms.Length.Dump();
ms2.Length.Dump();

ms.Write(ms2.GetBuffer(), (int)ms.Length, (int)ms2.Length);
ms.Length.Dump();

ms.Position = 0;

StreamReader rdr = new StreamReader(ms, Encoding.UTF8);
rdr.ReadToEnd().Dump();

结果是:

18
16
34
first memorystream□□□□□□□□□□□□□□□□

那么,问题是为什么不是“第一个内存流,第二个”呢?

我做错了什么?

【问题讨论】:

  • +1 非常易于使用的示例代码。

标签: c# string utf-8 buffer memorystream


【解决方案1】:

更改自 ms.Write(ms2.GetBuffer(), (int)ms.Length, (int)ms2.Length);

ms.Write(ms2.GetBuffer(), 0, (int)ms2.Length);

【讨论】:

  • 哇 => 一定要迟到了,我不能再阅读文档了。谢谢您的帮助。我没有意识到应用于缓冲区输入的偏移参数,而不是正在写入的流。谢谢!
【解决方案2】:

Write 的第二个参数是源缓冲区中的位置 - 所以它包含 0,因为它在第二个流结束后显式地显示。

public abstract void Write( byte[] buffer, int offset, int count )

偏移类型:System.Int32 开始将字节复制到当前流的缓冲区中从零开始的字节偏移量。

修复 - 为偏移量传递 0,因为您想从缓冲区的开头复制:

 ms.Write(ms2.GetBuffer(), 0, (int)ms2.Length);

【讨论】:

  • Yuuup,这是一个比我提出的更简单的解决方案。哈哈。 :P
【解决方案3】:

在 LinqPad 中运行,一切正常;阅读下面的评论以更好地理解解决方案...

string one = "first memorystream";
string two = ", and the second";

MemoryStream ms = new MemoryStream();
MemoryStream ms2 = new MemoryStream();

byte[] oneb = Encoding.UTF8.GetBytes(one);
byte[] twob = Encoding.UTF8.GetBytes(two);

ms.Write(oneb, 0, oneb.Length);
ms2.Write(twob, 0, twob.Length);

ms.Length.Dump("Stream 1, Length");
ms2.Length.Dump("Stream 2, Length");

ms2.Position = 0; // <-- You have to set the position back to 0 in order to write it, otherwise the stream just continuous where it left off, the end
ms2.CopyTo(ms, ms2.GetBuffer().Length); // <-- simple "merge"

/*
 * Don't need the below item anymore
 */ 
//ms.Write(ms2.GetBuffer(), (int)ms.Length, (int)ms2.Length);
ms.Length.Dump("Combined Length");

ms.Position = 0;

StreamReader rdr = new StreamReader(ms, Encoding.UTF8);
rdr.ReadToEnd().Dump();

【讨论】:

    猜你喜欢
    • 2013-02-21
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    相关资源
    最近更新 更多