zoukankan      html  css  js  c++  java
  • Stream 和 Byte[]互操作

    在.Net的IO操作中经常会用到Stream和Byte[],有两种形式:
    一.Stream->Byte[]:
         1.如果Stream的 Length属性可读,非常的简单,代码如下:

     1  private byte[] GetBytes(Stream stream)
     2        {
     3            if (stream.CanSeek)
     4            {
     5                Byte[] buffer = new byte[stream.Length];
     6                stream.Write(buffer, 0, buffer.Length);
     7                return buffer;
     8            }

     9            //用下面的方法
    10            return null;
    11        }

          2.如果Stream的 Length属性不可读,代码如下:

     1        private byte[] GetBytes(Stream stream)
     2        {
     3            using (MemoryStream mstream = new MemoryStream())
     4            {
     5                byte[] bytes = new byte[1024]; //此处不易设置太大或太小的值,且应该为2的次方
     6                if (stream.CanRead)
     7                {
     8                    while (true)
     9                    {
    10                        int length = stream.Read(bytes, 0, bytes.Length);
    11                        if (length <= 0)
    12                        {
    13                            break;
    14                        }

    15                        mstream.Write(bytes, 0, length);
    16                    }

    17                }

    18                return mstream.ToArray();
    19            }

    20        }

    21
    二.bytes-Stream:
       直接使用内存流即可,代码如下:
    MemoryStream ms=new MemoryStream(bytes)
  • 相关阅读:
    新的工作开始
    昨日的世界
    【Drools-开源业务规则引擎】入门实例(含源码)
    【cs229-Lecture7】支持向量机(SVM)
    【2014年12月6日】HR交流会
    【cs229-Lecture5】生成学习算法:1)高斯判别分析(GDA);2)朴素贝叶斯(NB)
    【图算法】Dijkstra算法及变形
    【图算法】综述
    【云迁移论文笔记】A Comparison of On-premise to Cloud Migration Approaches
    【云迁移论文笔记】Cloud Migration Research:A Systematic Review
  • 原文地址:https://www.cnblogs.com/kokoliu/p/939926.html
Copyright © 2011-2022 走看看