using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace StreamTest
{
class Program
{
static void Main(string[] args)
{
byte[] buffer = null;
string testString = "Stream! Hello world";
char[] readCharArray = null;
byte[] readBuffer = null;
string readString = string.Empty;
//MemoryStream
using (MemoryStream stream = new MemoryStream())
{
Console.WriteLine("初始化字符串为:{0}", testString);
//如果该流可写
if (stream.CanWrite)
{
//尝试将testString写入流中
buffer = Encoding.Default.GetBytes(testString);
//我们从该数组的第一个位置开始写,长度为3,写完之后stream 中便有了数据
stream.Write(buffer, 0, 3);
Console.WriteLine("现在Stream.Positon在第{0}位置", stream.Position + 1);
//从刚才结束的位置往后移3位,到第7位
long newPositionInStream = stream.CanSeek ? stream.Seek(3, SeekOrigin.Current) : 0;
Console.WriteLine("重新定位后Stream.Position在第{0}位置", newPositionInStream + 1);
if (newPositionInStream <buffer.Length)
{
stream.Write(buffer, (int)newPositionInStream, buffer.Length - (int)newPositionInStream);
}
stream.Position = 0;
//设置一个空盒子来接收流中的数据,长度根据stream的长度来决定
readBuffer = new byte\[stream.Length\];
//设置stream 总的读取数量
//注意! 这时候流已经把数据读到了readBuffer中
int count = stream.CanRead ? stream.Read(readBuffer, 0, readBuffer.Length) : 0;
int charCount = Encoding.Default.GetCharCount(readBuffer, 0, count);
readCharArray = new char\[charCount\];
Encoding.Default.GetDecoder().GetChars(readBuffer, 0, count, readCharArray, 0);
for (int i = 0; i < readCharArray.Length;i++ )
{
readString += readCharArray\[i\];
}
Console.WriteLine("读取的字符串为:{0}", readString);
}
stream.Close();
}
Console.ReadLine();
}
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章