1

我试图将一个内存流的内容附加到另一个内存流的内容,知道两个内存流都包含 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□□□□□□□□□□□□□□□□

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

我做错了什么?

4

3 回答 3

3

从 ms.Write(ms2.GetBuffer(), (int)ms.Length, (int)ms2.Length) 改变;

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

于 2013-10-01T03:05:24.297 回答
1

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

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

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

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

 ms.Write(ms2.GetBuffer(), 0, (int)ms2.Length);
于 2013-10-01T03:03:48.657 回答
0

在 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-10-01T03:02:11.513 回答