我搞不懂为什么只输出This,而且后面拼接的字符串都不输出
求解释。。
byte[] buffer = null;
string strTest = "This is Stream!";using (MemoryStream ms = new MemoryStream())
{
txtMsg.AppendText(string.Format("初始字符串为:{0}\n", strTest));
//如果流可写
if (ms.CanWrite)
{
//由于流是以二进制字节的形式存放,所以需要把字符串转换成Byte。
buffer = Encoding.UTF8.GetBytes(strTest);
//把buffer中的数据写到流中。位置从0开始,写4个长度
ms.Write(buffer, 0, 4);
txtMsg.AppendText(string.Format("现在ms.Position的位置为:{0}。{1}\n", ms.Position, ms.Length));
//移动流的位置。如果可以移动
long seekCount = 0;
if (ms.CanSeek)
{
//从刚才结束的位置开始,移动4个位置;返回一个长度
seekCount = ms.Seek(4, SeekOrigin.Current);
} if(seekCount < buffer.Length)
{
//从buffer的第4个位置开始读取,读buffer.Length - (int)ms.Length的长度
ms.Write(buffer, (int)ms.Length, buffer.Length - (int)seekCount);
}
ms.Position = 0;
//用来接受流中的数据,长度为流的长度
byte[] readBuffer = new byte[ms.Length];
int readCount = 0;
if (ms.CanRead)
{
readCount = ms.Read(readBuffer, 0, (int)ms.Length);
} string readString = Encoding.UTF8.GetString(readBuffer, 0, readCount);
txtMsg.AppendText("\n" + readString + "这是");
}
}
求解释。。
byte[] buffer = null;
string strTest = "This is Stream!";using (MemoryStream ms = new MemoryStream())
{
txtMsg.AppendText(string.Format("初始字符串为:{0}\n", strTest));
//如果流可写
if (ms.CanWrite)
{
//由于流是以二进制字节的形式存放,所以需要把字符串转换成Byte。
buffer = Encoding.UTF8.GetBytes(strTest);
//把buffer中的数据写到流中。位置从0开始,写4个长度
ms.Write(buffer, 0, 4);
txtMsg.AppendText(string.Format("现在ms.Position的位置为:{0}。{1}\n", ms.Position, ms.Length));
//移动流的位置。如果可以移动
long seekCount = 0;
if (ms.CanSeek)
{
//从刚才结束的位置开始,移动4个位置;返回一个长度
seekCount = ms.Seek(4, SeekOrigin.Current);
} if(seekCount < buffer.Length)
{
//从buffer的第4个位置开始读取,读buffer.Length - (int)ms.Length的长度
ms.Write(buffer, (int)ms.Length, buffer.Length - (int)seekCount);
}
ms.Position = 0;
//用来接受流中的数据,长度为流的长度
byte[] readBuffer = new byte[ms.Length];
int readCount = 0;
if (ms.CanRead)
{
readCount = ms.Read(readBuffer, 0, (int)ms.Length);
} string readString = Encoding.UTF8.GetString(readBuffer, 0, readCount);
txtMsg.AppendText("\n" + readString + "这是");
}
}
seekCount = ms.Seek(4, SeekOrigin.Current);
//-->
seekCount = ms.Seek(4, SeekOrigin.Begin);//第二个参数是参考位置,从开始便宜4个字节
就可以了。
//从刚才结束的位置开始,移动4个位置;返回一个长度
seekCount = ms.Seek(0, SeekOrigin.Current);
//流刚开始的位置是4啊,然后执行下面的,位置为8没错的。
seekCount = ms.Seek(4, SeekOrigin.Current);
/*然后继续写入到流中,不过有个疑问,这个第二个参数是指Buffer的位置还是流的位置?如果是Buffer的位置应该从Stream的S开始写,如果是流的位置应该是从流的第8个位置开始写,结果都不是。。求解释
ms.Write(buffer, (int)ms.Length, buffer.Length - (int)seekCount); //而且,我调试时候命名readString有后面的字符的,但是一输出只有This,难道是假象?
string readString = Encoding.UTF8.GetString(readBuffer, 0, readCount);
加个readString = readString.Replace("\0","");
//这个应该是从ms流的第四个位置开始读的
ms.Write(buffer, 4, count);
seekCount = ms.Seek(4, SeekOrigin.Current);
如果是接着写入,更本没必要偏移。当前流的位置本来就在最后,直接接着写就OK了
你从当前位置偏移4个字节,然后写入后面的字符串的时候中间就有4个字节的空白,最后4个字符无法输出。