C# Stream的使用之MemoryStream

MemoryStream位于System.IO命名空间,为系统内存提供流式的读写操作。常作为其他流数据交换时的中间对象操作。

1、MemoryStream类封装一个字节数组,在构造实例时可以使用一个字节数组作为参数,但是数组的长度无法调整。使用默认无参数构造函数创建实例,可以使用Write方法写入,随着字节数据的写入,数组的大小自动调整。

MemoryStream memStream = new MemoryStream(100)

2、在对MemoryStream类中数据流进行读取时,可以使用seek方法定位读取器的当前的位置,可以通过指定长度的数组一次性读取指定长度的数据。ReadByte方法每次读取一个字节,并将字节返回一个整数值。

代码实操

3、UnicodeEncoding类中定义了Unicode中UTF-16编码的相关功能。通过其中的方法将字符串转换为字节,也可以将字节转换为字符串。

字符串与字节数组间的互相转化:

        string str = "内存大小";
        byte[] temp = Encoding.UTF8.GetBytes (str);        // 字符串转化为字节数组
        string s = Encoding.UTF8.GetString (temp);        // 字节数组转化为字符串
        Debug.Log (s);

4、memorystream的两种写入方式 Write,WriteByte(同样读也有两种方式read和readbyte)

4.1 Write 将值从缓存区写入MemoryStream流对象。

     byte[] firstString = uniEncoding.GetBytes("一二三四五");
     MemoryStream memStream = new MemoryStream();
     memStream.Write(firstString, 0, firstString.Length);

4.2 WriteByte 从缓存区写入MemoytStream流对象一个字节

     byte[] secondString = uniEncoding.GetBytes("上山打老虎");
     MemoryStream memStream = new MemoryStream();
     count = 0;
     while (count < secondString.Length)
     {
        memStream.WriteByte(secondString[count++]);
     }

5 MemoryStream 是一个特例,MemoryStream中没有任何非托管资源,所以它的Dispose不调用也没关系。托管资源.Net会自动回收

6 代码实例

  public void Index()
        {
            int count;
            byte[] byteArray;
            char[] charArray;
            UnicodeEncoding uniEncoding = new UnicodeEncoding();
            // Create the data to write to the stream.
            byte[] firstString = uniEncoding.GetBytes("一二三四五");
            byte[] secondString = uniEncoding.GetBytes("上山打老虎");
            using (MemoryStream memStream = new MemoryStream(100))
            {

                //两种写入方式 
                //1 Write 将值从缓存区写入MemoryStream流对象。
                // Write the first string to the stream.
                memStream.Write(firstString, 0, firstString.Length);
                //2  WriteByte  从缓存区写入MemoytStream流对象一个字节。
                // Write the second string to the stream, byte by byte.
                count = 0;
                while (count < secondString.Length)
                {
                    memStream.WriteByte(secondString[count++]);
                }

                // Write the stream properties to the console.
                Console.WriteLine("Capacity={0},Length={1},Position={2}\n", memStream.Capacity.ToString(), memStream.Length.ToString(), memStream.Position.ToString());

                // Set the position to the beginning of the stream.
                memStream.Seek(0, SeekOrigin.Begin);

                // Read the first 20 bytes from the stream.
                byteArray = new byte[memStream.Length];
                count = memStream.Read(byteArray, 0, 20);

                // Read the remaining bytes, byte by byte.
                while (count < memStream.Length)
                {
                    byteArray[count++] = Convert.ToByte(memStream.ReadByte());
                }

                // Decode the byte array into a char array
                // and write it to the console.
                //字节转char
                charArray = new char[uniEncoding.GetCharCount(byteArray, 0, count)];

                //Decoder.GetChars 方法
                //Decoder.GetChars(Byte[], Int32, Int32, Char[], Int32)
                //在派生类中重写时,将指定字节数组的字节序列和内部缓冲区中的任何字节解码到指定的字符数组。
                //在派生类中重写时,将一个字节序列解码为一组字符。
                //Java里一个byte取值范围是 - 128~127, 而C#里一个byte是0~255.
                uniEncoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0);
                Console.WriteLine(charArray); Console.ReadKey();
            }

打印出来的结果

7 本地文件转内存流传送(FileStream与MemoryStream的联系)


   [HttpGet]
        public void GetFileToMemory()
        {
            FileStream fs = new FileStream(@"D:\我的收藏\host前期建设详细程序\HostWebDetail\WebAPI\文件1.txt", FileMode.Open, FileAccess.Read);
            //获取流的长度
            int nbytes = (int)fs.Length;
            //初始化一个字节
            byte[] bytearray = new byte[nbytes];
            //读取file中的流到byte中
            int byteread = fs.Read(bytearray, 0, nbytes);
            MemoryStream memStream = new MemoryStream(bytearray);



            //后面就是MemoryStream转string 有问题 暂未解决
            int count;
            byte[] byteArray;
            char[] charArray;
            UnicodeEncoding uniEncoding = new UnicodeEncoding();

            byteArray = new byte[memStream.Length];
            //这里为什么是6 因为这个字节读出来的长度是6 要匹配一致
            count = memStream.Read(byteArray, 0, 6);


            while (count < memStream.Length)
            {
                byteArray[count++] = Convert.ToByte(memStream.ReadByte());
            }

            // Decode the byte array into a char array
            // and write it to the console.
            //字节转char
            charArray = new char[uniEncoding.GetCharCount(byteArray, 0, count)];
            // string s = new string(charArray);
            uniEncoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0);
            Console.WriteLine(charArray); Console.ReadKey();
        }
posted @ 2022-06-09 14:05  原往  阅读(3189)  评论(0编辑  收藏  举报