码迷,mamicode.com
首页 > 其他好文 > 详细

关于Stream系列实战

时间:2016-07-07 00:56:35      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

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();
        }
    }
}

  

关于Stream系列实战

标签:

原文地址:http://www.cnblogs.com/gylhaut/p/5648469.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!